2006-05-02 09:31:56 +08:00
|
|
|
"""
|
|
|
|
MySQL database backend for Django.
|
|
|
|
|
|
|
|
Requires MySQLdb: http://sourceforge.net/projects/mysql-python
|
|
|
|
"""
|
2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import unicode_literals
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2012-02-28 05:15:25 +08:00
|
|
|
import datetime
|
2008-08-12 15:52:17 +08:00
|
|
|
import re
|
2010-01-29 23:45:55 +08:00
|
|
|
import sys
|
2012-03-17 17:11:24 +08:00
|
|
|
import warnings
|
2008-08-12 15:52:17 +08:00
|
|
|
|
2006-05-27 02:58:46 +08:00
|
|
|
try:
|
|
|
|
import MySQLdb as Database
|
2012-04-29 00:09:37 +08:00
|
|
|
except ImportError as e:
|
2006-05-27 02:58:46 +08:00
|
|
|
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
|
|
|
|
2012-04-21 11:04:10 +08:00
|
|
|
from django.utils.functional import cached_property
|
|
|
|
|
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
|
2012-04-21 11:04:10 +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
|
|
|
|
2012-02-29 16:57:48 +08:00
|
|
|
from MySQLdb.converters import conversions, Thing2Literal
|
2011-04-05 08:19:17 +08:00
|
|
|
from MySQLdb.constants import FIELD_TYPE, CLIENT
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2010-01-29 23:45:55 +08:00
|
|
|
from django.db import utils
|
2008-08-22 22:18:53 +08:00
|
|
|
from django.db.backends import *
|
2009-03-30 07:15:58 +08:00
|
|
|
from django.db.backends.signals import connection_created
|
2008-08-22 22:18:53 +08:00
|
|
|
from django.db.backends.mysql.client import DatabaseClient
|
|
|
|
from django.db.backends.mysql.creation import DatabaseCreation
|
|
|
|
from django.db.backends.mysql.introspection import DatabaseIntrospection
|
|
|
|
from django.db.backends.mysql.validation import DatabaseValidation
|
2012-06-09 21:59:52 +08:00
|
|
|
from django.utils.functional import cached_property
|
2008-11-16 16:50:06 +08:00
|
|
|
from django.utils.safestring import SafeString, SafeUnicode
|
2012-07-20 18:18:38 +08:00
|
|
|
from django.utils import six
|
2012-02-28 05:15:25 +08:00
|
|
|
from django.utils import timezone
|
2008-08-22 22:18:53 +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:
|
2012-03-17 17:11:24 +08:00
|
|
|
warnings.filterwarnings("error", category=Database.Warning)
|
2007-09-15 06:05:58 +08:00
|
|
|
|
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
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
# It's impossible to import datetime_or_None directly from MySQLdb.times
|
2012-02-28 05:15:25 +08:00
|
|
|
parse_datetime = conversions[FIELD_TYPE.DATETIME]
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2012-02-28 05:15:25 +08:00
|
|
|
def parse_datetime_with_timezone_support(value):
|
|
|
|
dt = parse_datetime(value)
|
2011-11-18 21:01:06 +08:00
|
|
|
# Confirm that dt is naive before overwriting its tzinfo.
|
2012-02-28 05:15:25 +08:00
|
|
|
if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
|
|
|
|
dt = dt.replace(tzinfo=timezone.utc)
|
2011-11-18 21:01:06 +08:00
|
|
|
return dt
|
|
|
|
|
2012-02-28 05:15:25 +08:00
|
|
|
def adapt_datetime_with_timezone_support(value, conv):
|
|
|
|
# Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
|
|
|
|
if settings.USE_TZ:
|
|
|
|
if timezone.is_naive(value):
|
2012-06-08 00:08:47 +08:00
|
|
|
warnings.warn("SQLite received a naive datetime (%s)"
|
|
|
|
" while time zone support is active." % value,
|
2012-02-28 05:15:25 +08:00
|
|
|
RuntimeWarning)
|
|
|
|
default_timezone = timezone.get_default_timezone()
|
|
|
|
value = timezone.make_aware(value, default_timezone)
|
|
|
|
value = value.astimezone(timezone.utc).replace(tzinfo=None)
|
2012-02-29 16:57:48 +08:00
|
|
|
return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S"), conv)
|
2012-02-28 05:15:25 +08:00
|
|
|
|
2008-11-16 16:50:06 +08:00
|
|
|
# MySQLdb-1.2.1 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. We also need to
|
|
|
|
# add special handling for SafeUnicode and SafeString as MySQLdb's type
|
|
|
|
# checking is too tight to catch those (see Django ticket #6052).
|
2011-11-18 21:01:06 +08:00
|
|
|
# Finally, MySQLdb always returns naive datetime objects. However, when
|
|
|
|
# timezone support is active, Django expects timezone-aware datetime objects.
|
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,
|
2012-02-28 05:15:25 +08:00
|
|
|
FIELD_TYPE.DATETIME: parse_datetime_with_timezone_support,
|
|
|
|
datetime.datetime: adapt_datetime_with_timezone_support,
|
2008-08-13 00:28:52 +08:00
|
|
|
})
|
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
|
|
|
|
2008-08-29 12:30:07 +08:00
|
|
|
class CursorWrapper(object):
|
|
|
|
"""
|
|
|
|
A thin wrapper around MySQLdb's normal cursor class so that we can catch
|
|
|
|
particular exception instances and reraise them with the right types.
|
|
|
|
|
|
|
|
Implemented as a wrapper, rather than a subclass, so that we aren't stuck
|
|
|
|
to the particular underlying representation returned by Connection.cursor().
|
|
|
|
"""
|
|
|
|
codes_for_integrityerror = (1048,)
|
|
|
|
|
|
|
|
def __init__(self, cursor):
|
|
|
|
self.cursor = cursor
|
|
|
|
|
|
|
|
def execute(self, query, args=None):
|
|
|
|
try:
|
|
|
|
return self.cursor.execute(query, args)
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.IntegrityError as e:
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.OperationalError as e:
|
2008-08-29 12:30:07 +08:00
|
|
|
# Map some error codes to IntegrityError, since they seem to be
|
|
|
|
# misclassified and Django would prefer the more logical place.
|
|
|
|
if e[0] in self.codes_for_integrityerror:
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
|
|
|
|
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.DatabaseError as e:
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
|
2008-08-29 12:30:07 +08:00
|
|
|
|
|
|
|
def executemany(self, query, args):
|
|
|
|
try:
|
|
|
|
return self.cursor.executemany(query, args)
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.IntegrityError as e:
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.OperationalError as e:
|
2008-08-29 12:30:07 +08:00
|
|
|
# Map some error codes to IntegrityError, since they seem to be
|
|
|
|
# misclassified and Django would prefer the more logical place.
|
|
|
|
if e[0] in self.codes_for_integrityerror:
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
|
|
|
|
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
|
2012-04-29 00:09:37 +08:00
|
|
|
except Database.DatabaseError as e:
|
2012-07-22 03:06:13 +08:00
|
|
|
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
|
2008-08-29 12:30:07 +08:00
|
|
|
|
|
|
|
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):
|
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
|
2009-01-15 19:06:34 +08:00
|
|
|
allows_group_by_pk = True
|
2008-09-01 08:49:03 +08:00
|
|
|
related_fields_match_type = True
|
2010-04-05 01:05:43 +08:00
|
|
|
allow_sliced_subqueries = False
|
2011-09-10 03:22:28 +08:00
|
|
|
has_bulk_insert = True
|
2011-04-21 04:42:07 +08:00
|
|
|
has_select_for_update = True
|
|
|
|
has_select_for_update_nowait = False
|
2010-10-11 20:55:17 +08:00
|
|
|
supports_forward_references = False
|
|
|
|
supports_long_model_names = False
|
|
|
|
supports_microsecond_precision = False
|
|
|
|
supports_regex_backreferencing = False
|
|
|
|
supports_date_lookup_using_string = False
|
|
|
|
supports_timezones = False
|
|
|
|
requires_explicit_null_ordering_when_grouping = True
|
|
|
|
allows_primary_key_0 = False
|
2012-04-21 11:04:10 +08:00
|
|
|
uses_savepoints = True
|
2007-08-20 10:20:33 +08:00
|
|
|
|
2012-01-05 08:45:31 +08:00
|
|
|
def __init__(self, connection):
|
|
|
|
super(DatabaseFeatures, self).__init__(connection)
|
|
|
|
|
2012-06-09 21:59:52 +08:00
|
|
|
@cached_property
|
2012-01-05 08:45:31 +08:00
|
|
|
def _mysql_storage_engine(self):
|
|
|
|
"Internal method used in Django tests. Don't rely on this from your code"
|
2012-06-09 21:59:52 +08:00
|
|
|
cursor = self.connection.cursor()
|
|
|
|
cursor.execute('CREATE TABLE INTROSPECT_TEST (X INT)')
|
|
|
|
# This command is MySQL specific; the second column
|
|
|
|
# will tell you the default table type of the created
|
|
|
|
# table. Since all Django's test tables will have the same
|
|
|
|
# table type, that's enough to evaluate the feature.
|
|
|
|
cursor.execute("SHOW TABLE STATUS WHERE Name='INTROSPECT_TEST'")
|
|
|
|
result = cursor.fetchone()
|
|
|
|
cursor.execute('DROP TABLE INTROSPECT_TEST')
|
|
|
|
return result[1]
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def can_introspect_foreign_keys(self):
|
2011-02-01 22:42:52 +08:00
|
|
|
"Confirm support for introspected foreign keys"
|
2012-06-09 21:59:52 +08:00
|
|
|
return self._mysql_storage_engine != 'MyISAM'
|
2011-02-01 22:42:52 +08:00
|
|
|
|
2007-08-20 06:29:57 +08:00
|
|
|
class DatabaseOperations(BaseDatabaseOperations):
|
2010-04-01 23:10:53 +08:00
|
|
|
compiler_module = "django.db.backends.mysql.compiler"
|
|
|
|
|
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
|
2009-02-08 13:08:06 +08:00
|
|
|
if lookup_type == 'week_day':
|
|
|
|
# DAYOFWEEK() returns an integer, 1-7, Sunday=1.
|
|
|
|
# Note: WEEKDAY() returns 0-6, Monday=0.
|
|
|
|
return "DAYOFWEEK(%s)" % field_name
|
|
|
|
else:
|
|
|
|
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
|
|
|
|
|
2010-12-22 11:34:04 +08:00
|
|
|
def date_interval_sql(self, sql, connector, timedelta):
|
|
|
|
return "(%s %s INTERVAL '%d 0:0:%d:%d' DAY_MICROSECOND)" % (sql, connector,
|
|
|
|
timedelta.days, timedelta.seconds, timedelta.microseconds)
|
|
|
|
|
2007-08-20 07:07:34 +08:00
|
|
|
def drop_foreignkey_sql(self):
|
|
|
|
return "DROP FOREIGN KEY"
|
|
|
|
|
2008-12-10 13:19:27 +08:00
|
|
|
def force_no_ordering(self):
|
|
|
|
"""
|
|
|
|
"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
|
|
|
|
columns. If no ordering would otherwise be applied, we don't want any
|
|
|
|
implicit sorting going on.
|
|
|
|
"""
|
|
|
|
return ["NULL"]
|
|
|
|
|
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
|
|
|
|
|
2011-04-22 20:14:54 +08:00
|
|
|
def last_executed_query(self, cursor, sql, params):
|
|
|
|
# With MySQLdb, cursor objects have an (undocumented) "_last_executed"
|
|
|
|
# attribute where the exact query sent to the database is saved.
|
|
|
|
# See MySQLdb/cursors.py in the source distribution.
|
2012-06-13 17:36:27 +08:00
|
|
|
return cursor._last_executed.decode('utf-8')
|
2011-04-22 20:14:54 +08:00
|
|
|
|
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
|
2012-07-20 18:45:19 +08:00
|
|
|
return 18446744073709551615
|
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
|
|
|
|
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;')
|
|
|
|
|
2012-04-25 00:47:31 +08:00
|
|
|
# Truncate already resets the AUTO_INCREMENT field from
|
|
|
|
# MySQL version 5.0.13 onwards. Refs #16961.
|
|
|
|
if self.connection.mysql_version < (5,0,13):
|
|
|
|
sql.extend(
|
|
|
|
["%s %s %s %s %s;" % \
|
|
|
|
(style.SQL_KEYWORD('ALTER'),
|
|
|
|
style.SQL_KEYWORD('TABLE'),
|
|
|
|
style.SQL_TABLE(self.quote_name(sequence['table'])),
|
|
|
|
style.SQL_KEYWORD('AUTO_INCREMENT'),
|
|
|
|
style.SQL_FIELD('= 1'),
|
|
|
|
) for sequence in sequences])
|
2007-08-20 08:15:53 +08:00
|
|
|
return sql
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2012-04-25 02:03:14 +08:00
|
|
|
def validate_autopk_value(self, value):
|
|
|
|
# MySQLism: zero in AUTO_INCREMENT field does not work. Refs #17653.
|
|
|
|
if value == 0:
|
|
|
|
raise ValueError('The database backend does not accept 0 as a '
|
|
|
|
'value for AutoField.')
|
|
|
|
return value
|
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
def value_to_db_datetime(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
2008-11-16 16:50:06 +08:00
|
|
|
|
2008-09-02 01:48:39 +08:00
|
|
|
# MySQL doesn't support tz-aware datetimes
|
2012-02-28 05:15:25 +08:00
|
|
|
if timezone.is_aware(value):
|
2011-11-18 21:01:06 +08:00
|
|
|
if settings.USE_TZ:
|
2012-02-28 05:15:25 +08:00
|
|
|
value = value.astimezone(timezone.utc).replace(tzinfo=None)
|
2011-11-18 21:01:06 +08:00
|
|
|
else:
|
|
|
|
raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")
|
2008-09-02 01:48:39 +08:00
|
|
|
|
|
|
|
# MySQL doesn't support microseconds
|
2012-07-20 20:48:51 +08:00
|
|
|
return six.text_type(value.replace(microsecond=0))
|
2008-07-29 13:09:29 +08:00
|
|
|
|
|
|
|
def value_to_db_time(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
2008-11-16 16:50:06 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
# MySQL doesn't support tz-aware times
|
2012-02-28 05:15:25 +08:00
|
|
|
if timezone.is_aware(value):
|
2011-11-18 21:01:06 +08:00
|
|
|
raise ValueError("MySQL backend does not support timezone-aware times.")
|
2008-11-16 16:50:06 +08:00
|
|
|
|
2008-09-02 01:48:39 +08:00
|
|
|
# MySQL doesn't support microseconds
|
2012-07-20 20:48:51 +08:00
|
|
|
return six.text_type(value.replace(microsecond=0))
|
2008-07-29 13:09:29 +08:00
|
|
|
|
|
|
|
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]
|
|
|
|
|
2010-04-28 20:08:30 +08:00
|
|
|
def max_name_length(self):
|
|
|
|
return 64
|
|
|
|
|
2011-09-10 03:22:28 +08:00
|
|
|
def bulk_insert_sql(self, fields, num_values):
|
|
|
|
items_sql = "(%s)" % ", ".join(["%s"] * len(fields))
|
|
|
|
return "VALUES " + ", ".join([items_sql] * num_values)
|
|
|
|
|
2012-01-05 08:45:31 +08:00
|
|
|
def savepoint_create_sql(self, sid):
|
|
|
|
return "SAVEPOINT %s" % sid
|
|
|
|
|
|
|
|
def savepoint_commit_sql(self, sid):
|
|
|
|
return "RELEASE SAVEPOINT %s" % sid
|
|
|
|
|
|
|
|
def savepoint_rollback_sql(self, sid):
|
|
|
|
return "ROLLBACK TO SAVEPOINT %s" % sid
|
|
|
|
|
2007-08-20 05:30:57 +08:00
|
|
|
class DatabaseWrapper(BaseDatabaseWrapper):
|
2010-10-11 20:55:17 +08:00
|
|
|
vendor = 'mysql'
|
2007-08-20 11:26:55 +08:00
|
|
|
operators = {
|
2008-08-12 15:52:33 +08:00
|
|
|
'exact': '= %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
|
|
|
|
2009-03-11 19:03:36 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(DatabaseWrapper, self).__init__(*args, **kwargs)
|
2008-08-12 15:52:17 +08:00
|
|
|
|
2009-03-11 11:39:34 +08:00
|
|
|
self.server_version = None
|
2010-10-11 20:55:17 +08:00
|
|
|
self.features = DatabaseFeatures(self)
|
2011-04-05 08:19:17 +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 = DatabaseValidation(self)
|
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
|
|
|
|
|
2009-03-11 11:39:34 +08:00
|
|
|
def _cursor(self):
|
2011-09-11 02:58:30 +08:00
|
|
|
new_connection = False
|
2006-05-02 09:31:56 +08:00
|
|
|
if not self._valid_connection():
|
2011-09-11 02:58:30 +08:00
|
|
|
new_connection = True
|
2006-05-02 09:31:56 +08:00
|
|
|
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
|
|
|
}
|
2009-03-11 11:39:34 +08:00
|
|
|
settings_dict = self.settings_dict
|
2009-12-22 23:18:51 +08:00
|
|
|
if settings_dict['USER']:
|
|
|
|
kwargs['user'] = settings_dict['USER']
|
|
|
|
if settings_dict['NAME']:
|
|
|
|
kwargs['db'] = settings_dict['NAME']
|
|
|
|
if settings_dict['PASSWORD']:
|
|
|
|
kwargs['passwd'] = settings_dict['PASSWORD']
|
|
|
|
if settings_dict['HOST'].startswith('/'):
|
|
|
|
kwargs['unix_socket'] = settings_dict['HOST']
|
|
|
|
elif settings_dict['HOST']:
|
|
|
|
kwargs['host'] = settings_dict['HOST']
|
|
|
|
if settings_dict['PORT']:
|
|
|
|
kwargs['port'] = int(settings_dict['PORT'])
|
2009-04-12 10:15:14 +08:00
|
|
|
# We need the number of potentially affected rows after an
|
|
|
|
# "UPDATE", not the number of changed rows.
|
|
|
|
kwargs['client_flag'] = CLIENT.FOUND_ROWS
|
2009-12-22 23:18:51 +08:00
|
|
|
kwargs.update(settings_dict['OPTIONS'])
|
2006-05-02 09:31:56 +08:00
|
|
|
self.connection = Database.connect(**kwargs)
|
2012-07-20 20:48:51 +08:00
|
|
|
self.connection.encoders[SafeUnicode] = self.connection.encoders[six.text_type]
|
|
|
|
self.connection.encoders[SafeString] = self.connection.encoders[bytes]
|
2010-08-30 21:21:18 +08:00
|
|
|
connection_created.send(sender=self.__class__, connection=self)
|
2011-09-11 02:58:30 +08:00
|
|
|
cursor = self.connection.cursor()
|
|
|
|
if new_connection:
|
|
|
|
# SQL_AUTO_IS_NULL in MySQL controls whether an AUTO_INCREMENT column
|
|
|
|
# on a recently-inserted row will return when the field is tested for
|
|
|
|
# NULL. Disabling this value brings this aspect of MySQL in line with
|
|
|
|
# SQL standards.
|
|
|
|
cursor.execute('SET SQL_AUTO_IS_NULL = 0')
|
|
|
|
return CursorWrapper(cursor)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
2012-04-21 11:04:10 +08:00
|
|
|
@cached_property
|
|
|
|
def mysql_version(self):
|
2006-09-27 10:42:31 +08:00
|
|
|
if not self.server_version:
|
2012-05-27 23:24:35 +08:00
|
|
|
new_connection = False
|
2006-09-27 10:42:31 +08:00
|
|
|
if not self._valid_connection():
|
2012-05-27 23:24:35 +08:00
|
|
|
# Ensure we have a connection with the DB by using a temporary
|
|
|
|
# cursor
|
|
|
|
new_connection = True
|
2012-04-21 11:04:10 +08:00
|
|
|
self.cursor().close()
|
2012-05-27 23:24:35 +08:00
|
|
|
server_info = self.connection.get_server_info()
|
|
|
|
if new_connection:
|
|
|
|
# Make sure we close the connection
|
|
|
|
self.connection.close()
|
|
|
|
self.connection = None
|
|
|
|
m = server_version_re.match(server_info)
|
2006-09-27 10:42:31 +08:00
|
|
|
if not m:
|
2012-05-27 23:24:35 +08:00
|
|
|
raise Exception('Unable to determine MySQL version from version string %r' % 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
|
2011-08-07 08:43:26 +08:00
|
|
|
|
|
|
|
def disable_constraint_checking(self):
|
|
|
|
"""
|
|
|
|
Disables foreign key checks, primarily for use in adding rows with forward references. Always returns True,
|
|
|
|
to indicate constraint checks need to be re-enabled.
|
|
|
|
"""
|
|
|
|
self.cursor().execute('SET foreign_key_checks=0')
|
|
|
|
return True
|
|
|
|
|
|
|
|
def enable_constraint_checking(self):
|
|
|
|
"""
|
|
|
|
Re-enable foreign key checks after they have been disabled.
|
|
|
|
"""
|
|
|
|
self.cursor().execute('SET foreign_key_checks=1')
|
|
|
|
|
|
|
|
def check_constraints(self, table_names=None):
|
|
|
|
"""
|
2011-08-09 01:08:35 +08:00
|
|
|
Checks each table name in `table_names` for rows with invalid foreign key references. This method is
|
2011-08-07 08:43:26 +08:00
|
|
|
intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
|
|
|
|
determine if rows with invalid references were entered while constraint checks were off.
|
|
|
|
|
|
|
|
Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides
|
|
|
|
detailed information about the invalid reference in the error message.
|
|
|
|
|
|
|
|
Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS
|
|
|
|
ALL IMMEDIATE")
|
|
|
|
"""
|
|
|
|
cursor = self.cursor()
|
|
|
|
if table_names is None:
|
2012-04-29 07:11:55 +08:00
|
|
|
table_names = self.introspection.table_names(cursor)
|
2011-08-07 08:43:26 +08:00
|
|
|
for table_name in table_names:
|
|
|
|
primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
|
|
|
|
if not primary_key_column_name:
|
|
|
|
continue
|
|
|
|
key_columns = self.introspection.get_key_columns(cursor, table_name)
|
|
|
|
for column_name, referenced_table_name, referenced_column_name in key_columns:
|
|
|
|
cursor.execute("""
|
|
|
|
SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
|
|
|
|
LEFT JOIN `%s` as REFERRED
|
|
|
|
ON (REFERRING.`%s` = REFERRED.`%s`)
|
|
|
|
WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
|
|
|
|
% (primary_key_column_name, column_name, table_name, referenced_table_name,
|
|
|
|
column_name, referenced_column_name, column_name, referenced_column_name))
|
|
|
|
for bad_row in cursor.fetchall():
|
|
|
|
raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
|
|
|
|
"foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
|
|
|
|
% (table_name, bad_row[0],
|
|
|
|
table_name, column_name, bad_row[1],
|
|
|
|
referenced_table_name, referenced_column_name))
|