2006-05-02 09:31:56 +08:00
|
|
|
"""
|
|
|
|
MySQL database backend for Django.
|
|
|
|
|
|
|
|
Requires MySQLdb: http://sourceforge.net/projects/mysql-python
|
|
|
|
"""
|
|
|
|
|
2007-08-20 10:20:33 +08:00
|
|
|
from django.db.backends import BaseDatabaseWrapper, BaseDatabaseFeatures, BaseDatabaseOperations, util
|
2006-05-27 02:58:46 +08:00
|
|
|
try:
|
|
|
|
import MySQLdb as Database
|
|
|
|
except ImportError, e:
|
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2007-08-20 11:32:06 +08:00
|
|
|
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
|
2007-03-19 03:16:47 +08:00
|
|
|
|
|
|
|
# We want version (1, 2, 1, 'final', 2) or later. We can't just use
|
|
|
|
# lexicographic ordering in this check because then (1, 2, 1, 'gamma')
|
|
|
|
# inadvertently passes the version test.
|
|
|
|
version = Database.version_info
|
2007-05-21 09:29:58 +08:00
|
|
|
if (version < (1,2,1) or (version[:3] == (1, 2, 1) and
|
2007-03-19 03:16:47 +08:00
|
|
|
(len(version) < 5 or version[3] != 'final' or version[4] < 2))):
|
2008-03-24 22:02:44 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
|
|
|
raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__)
|
2007-03-14 20:08:19 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from MySQLdb.converters import conversions
|
|
|
|
from MySQLdb.constants import FIELD_TYPE
|
2006-09-27 10:42:31 +08:00
|
|
|
import re
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2007-09-15 06:05:58 +08:00
|
|
|
# Raise exceptions for database warnings if DEBUG is on
|
2007-09-15 07:02:39 +08:00
|
|
|
from django.conf import settings
|
2007-09-15 06:05:58 +08:00
|
|
|
if settings.DEBUG:
|
|
|
|
from warnings import filterwarnings
|
|
|
|
filterwarnings("error", category=Database.Warning)
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
DatabaseError = Database.DatabaseError
|
2007-04-25 18:18:56 +08:00
|
|
|
IntegrityError = Database.IntegrityError
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2007-03-14 20:08:19 +08:00
|
|
|
# MySQLdb-1.2.1 supports the Python boolean type, and only uses datetime
|
|
|
|
# module for time-related columns; older versions could have used mx.DateTime
|
|
|
|
# or strings if there were no datetime module. However, MySQLdb still returns
|
|
|
|
# TIME columns as timedelta -- they are more like timedelta in terms of actual
|
|
|
|
# behavior as they are signed and include days -- and Django expects time, so
|
|
|
|
# we still need to override that.
|
2006-05-02 09:31:56 +08:00
|
|
|
django_conversions = conversions.copy()
|
|
|
|
django_conversions.update({
|
|
|
|
FIELD_TYPE.TIME: util.typecast_time,
|
2007-05-21 09:29:58 +08:00
|
|
|
FIELD_TYPE.DECIMAL: util.typecast_decimal,
|
|
|
|
FIELD_TYPE.NEWDECIMAL: util.typecast_decimal,
|
2006-05-02 09:31:56 +08:00
|
|
|
})
|
|
|
|
|
2006-09-27 10:42:31 +08:00
|
|
|
# This should match the numerical portion of the version numbers (we can treat
|
|
|
|
# versions like 5.0.24 and 5.0.24a as the same). Based on the list of version
|
|
|
|
# at http://dev.mysql.com/doc/refman/4.1/en/news.html and
|
|
|
|
# http://dev.mysql.com/doc/refman/5.0/en/news.html .
|
|
|
|
server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
|
|
|
|
|
2007-03-14 20:08:19 +08:00
|
|
|
# MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
|
|
|
|
# MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
|
|
|
|
# point is to raise Warnings as exceptions, this can be done with the Python
|
|
|
|
# warning module, and this is setup when the connection is created, and the
|
|
|
|
# standard util.CursorDebugWrapper can be used. Also, using sql_mode
|
|
|
|
# TRADITIONAL will automatically cause most warnings to be treated as errors.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2007-08-20 10:20:33 +08:00
|
|
|
class DatabaseFeatures(BaseDatabaseFeatures):
|
2007-11-04 13:05:24 +08:00
|
|
|
inline_fk_references = False
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
empty_fetchmany_value = ()
|
2008-04-28 19:51:52 +08:00
|
|
|
update_can_self_select = False
|
2007-08-20 10:20:33 +08:00
|
|
|
|
2007-08-20 06:29:57 +08:00
|
|
|
class DatabaseOperations(BaseDatabaseOperations):
|
2007-08-20 06:40:06 +08:00
|
|
|
def date_extract_sql(self, lookup_type, field_name):
|
|
|
|
# http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
|
|
|
|
return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
|
2007-08-20 06:29:57 +08:00
|
|
|
|
2007-08-20 06:47:43 +08:00
|
|
|
def date_trunc_sql(self, lookup_type, field_name):
|
|
|
|
fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
|
|
|
|
format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
|
|
|
|
format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
|
|
|
|
try:
|
|
|
|
i = fields.index(lookup_type) + 1
|
|
|
|
except ValueError:
|
|
|
|
sql = field_name
|
|
|
|
else:
|
|
|
|
format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
|
|
|
|
sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
|
|
|
|
return sql
|
|
|
|
|
2007-08-20 07:07:34 +08:00
|
|
|
def drop_foreignkey_sql(self):
|
|
|
|
return "DROP FOREIGN KEY"
|
|
|
|
|
2007-08-20 07:13:06 +08:00
|
|
|
def fulltext_search_sql(self, field_name):
|
|
|
|
return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name
|
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
def no_limit_value(self):
|
|
|
|
# 2**64 - 1, as recommended by the MySQL documentation
|
|
|
|
return 18446744073709551615L
|
|
|
|
|
2007-08-20 09:03:33 +08:00
|
|
|
def quote_name(self, name):
|
|
|
|
if name.startswith("`") and name.endswith("`"):
|
|
|
|
return name # Quoting once is enough.
|
|
|
|
return "`%s`" % name
|
|
|
|
|
2007-08-20 08:04:20 +08:00
|
|
|
def random_function_sql(self):
|
|
|
|
return 'RAND()'
|
|
|
|
|
2007-08-20 08:15:53 +08:00
|
|
|
def sql_flush(self, style, tables, sequences):
|
|
|
|
# NB: The generated SQL below is specific to MySQL
|
|
|
|
# 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements
|
|
|
|
# to clear all tables of all data
|
|
|
|
if tables:
|
|
|
|
sql = ['SET FOREIGN_KEY_CHECKS = 0;']
|
|
|
|
for table in tables:
|
2007-08-20 09:03:33 +08:00
|
|
|
sql.append('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(self.quote_name(table))))
|
2007-08-20 08:15:53 +08:00
|
|
|
sql.append('SET FOREIGN_KEY_CHECKS = 1;')
|
|
|
|
|
|
|
|
# 'ALTER TABLE table AUTO_INCREMENT = 1;'... style SQL statements
|
|
|
|
# to reset sequence indices
|
|
|
|
sql.extend(["%s %s %s %s %s;" % \
|
|
|
|
(style.SQL_KEYWORD('ALTER'),
|
|
|
|
style.SQL_KEYWORD('TABLE'),
|
2007-08-20 09:03:33 +08:00
|
|
|
style.SQL_TABLE(self.quote_name(sequence['table'])),
|
2007-08-20 08:15:53 +08:00
|
|
|
style.SQL_KEYWORD('AUTO_INCREMENT'),
|
|
|
|
style.SQL_FIELD('= 1'),
|
|
|
|
) for sequence in sequences])
|
|
|
|
return sql
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
def value_to_db_datetime(self, value):
|
|
|
|
# MySQL doesn't support microseconds
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return unicode(value.replace(microsecond=0))
|
|
|
|
|
|
|
|
def value_to_db_time(self, value):
|
|
|
|
# MySQL doesn't support microseconds
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return unicode(value.replace(microsecond=0))
|
|
|
|
|
|
|
|
def year_lookup_bounds(self, value):
|
|
|
|
# Again, no microseconds
|
|
|
|
first = '%s-01-01 00:00:00'
|
|
|
|
second = '%s-12-31 23:59:59.99'
|
|
|
|
return [first % value, second % value]
|
|
|
|
|
2007-08-20 05:30:57 +08:00
|
|
|
class DatabaseWrapper(BaseDatabaseWrapper):
|
2007-08-20 10:20:33 +08:00
|
|
|
features = DatabaseFeatures()
|
2007-08-20 06:29:57 +08:00
|
|
|
ops = DatabaseOperations()
|
2007-08-20 11:26:55 +08:00
|
|
|
operators = {
|
2008-06-30 18:25:35 +08:00
|
|
|
'exact': '= BINARY %s',
|
2007-08-20 11:26:55 +08:00
|
|
|
'iexact': 'LIKE %s',
|
|
|
|
'contains': 'LIKE BINARY %s',
|
|
|
|
'icontains': 'LIKE %s',
|
|
|
|
'regex': 'REGEXP BINARY %s',
|
|
|
|
'iregex': 'REGEXP %s',
|
|
|
|
'gt': '> %s',
|
|
|
|
'gte': '>= %s',
|
|
|
|
'lt': '< %s',
|
|
|
|
'lte': '<= %s',
|
|
|
|
'startswith': 'LIKE BINARY %s',
|
|
|
|
'endswith': 'LIKE BINARY %s',
|
|
|
|
'istartswith': 'LIKE %s',
|
|
|
|
'iendswith': 'LIKE %s',
|
|
|
|
}
|
2007-08-20 06:29:57 +08:00
|
|
|
|
2006-11-07 13:17:38 +08:00
|
|
|
def __init__(self, **kwargs):
|
2007-08-20 05:30:57 +08:00
|
|
|
super(DatabaseWrapper, self).__init__(**kwargs)
|
2006-09-27 10:42:31 +08:00
|
|
|
self.server_version = None
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def _valid_connection(self):
|
|
|
|
if self.connection is not None:
|
|
|
|
try:
|
|
|
|
self.connection.ping()
|
|
|
|
return True
|
|
|
|
except DatabaseError:
|
|
|
|
self.connection.close()
|
|
|
|
self.connection = None
|
|
|
|
return False
|
|
|
|
|
2007-08-20 05:30:57 +08:00
|
|
|
def _cursor(self, settings):
|
2006-05-02 09:31:56 +08:00
|
|
|
if not self._valid_connection():
|
|
|
|
kwargs = {
|
|
|
|
'conv': django_conversions,
|
2007-03-21 07:32:39 +08:00
|
|
|
'charset': 'utf8',
|
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
|
|
|
'use_unicode': True,
|
2006-05-02 09:31:56 +08:00
|
|
|
}
|
2007-03-14 20:08:19 +08:00
|
|
|
if settings.DATABASE_USER:
|
|
|
|
kwargs['user'] = settings.DATABASE_USER
|
|
|
|
if settings.DATABASE_NAME:
|
|
|
|
kwargs['db'] = settings.DATABASE_NAME
|
|
|
|
if settings.DATABASE_PASSWORD:
|
|
|
|
kwargs['passwd'] = settings.DATABASE_PASSWORD
|
2006-05-02 09:31:56 +08:00
|
|
|
if settings.DATABASE_HOST.startswith('/'):
|
|
|
|
kwargs['unix_socket'] = settings.DATABASE_HOST
|
2007-03-14 20:08:19 +08:00
|
|
|
elif settings.DATABASE_HOST:
|
2006-05-02 09:31:56 +08:00
|
|
|
kwargs['host'] = settings.DATABASE_HOST
|
|
|
|
if settings.DATABASE_PORT:
|
|
|
|
kwargs['port'] = int(settings.DATABASE_PORT)
|
2006-11-07 13:17:38 +08:00
|
|
|
kwargs.update(self.options)
|
2006-05-02 09:31:56 +08:00
|
|
|
self.connection = Database.connect(**kwargs)
|
2007-08-20 05:30:57 +08:00
|
|
|
cursor = self.connection.cursor()
|
2006-05-02 09:31:56 +08:00
|
|
|
return cursor
|
|
|
|
|
|
|
|
def _rollback(self):
|
2007-08-20 05:30:57 +08:00
|
|
|
try:
|
|
|
|
BaseDatabaseWrapper._rollback(self)
|
|
|
|
except Database.NotSupportedError:
|
|
|
|
pass
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-09-27 10:42:31 +08:00
|
|
|
def get_server_version(self):
|
|
|
|
if not self.server_version:
|
|
|
|
if not self._valid_connection():
|
|
|
|
self.cursor()
|
|
|
|
m = server_version_re.match(self.connection.get_server_info())
|
|
|
|
if not m:
|
|
|
|
raise Exception('Unable to determine MySQL version from version string %r' % self.connection.get_server_info())
|
2006-09-27 10:47:19 +08:00
|
|
|
self.server_version = tuple([int(x) for x in m.groups()])
|
2006-09-27 10:42:31 +08:00
|
|
|
return self.server_version
|