2006-05-02 09:31:56 +08:00
|
|
|
"""
|
|
|
|
MySQL database backend for Django.
|
|
|
|
|
2014-10-27 21:01:12 +08:00
|
|
|
Requires mysqlclient: https://pypi.python.org/pypi/mysqlclient/
|
2006-05-02 09:31:56 +08:00
|
|
|
"""
|
2008-08-12 15:52:17 +08:00
|
|
|
import re
|
|
|
|
|
2017-01-17 01:48:41 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2015-01-13 04:20:40 +08:00
|
|
|
from django.db import utils
|
|
|
|
from django.db.backends import utils as backend_utils
|
|
|
|
from django.db.backends.base.base import BaseDatabaseWrapper
|
|
|
|
from django.utils.functional import cached_property
|
|
|
|
|
2006-05-27 02:58:46 +08:00
|
|
|
try:
|
|
|
|
import MySQLdb as Database
|
2017-01-08 03:13:29 +08:00
|
|
|
except ImportError as err:
|
2016-06-29 07:31:27 +08:00
|
|
|
raise ImproperlyConfigured(
|
2017-01-08 03:13:29 +08:00
|
|
|
'Error loading MySQLdb module.\n'
|
2017-01-25 23:16:10 +08:00
|
|
|
'Did you install mysqlclient?'
|
2017-01-08 03:13:29 +08:00
|
|
|
) from err
|
2007-03-19 03:16:47 +08:00
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip
|
2016-12-31 07:04:09 +08:00
|
|
|
from MySQLdb.converters import conversions # isort:skip
|
2015-01-13 04:20:40 +08:00
|
|
|
|
|
|
|
# Some of these import MySQLdb, so import them after checking if it's installed.
|
2015-01-28 20:35:27 +08:00
|
|
|
from .client import DatabaseClient # isort:skip
|
|
|
|
from .creation import DatabaseCreation # isort:skip
|
|
|
|
from .features import DatabaseFeatures # isort:skip
|
|
|
|
from .introspection import DatabaseIntrospection # isort:skip
|
|
|
|
from .operations import DatabaseOperations # isort:skip
|
2015-02-09 20:52:34 +08:00
|
|
|
from .schema import DatabaseSchemaEditor # isort:skip
|
2015-01-28 20:35:27 +08:00
|
|
|
from .validation import DatabaseValidation # isort:skip
|
2015-01-13 04:20:40 +08:00
|
|
|
|
2007-03-19 03:16:47 +08:00
|
|
|
version = Database.version_info
|
2017-01-25 23:16:10 +08:00
|
|
|
if version < (1, 3, 3):
|
|
|
|
raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)
|
2007-03-14 20:08:19 +08:00
|
|
|
|
2008-08-22 22:18:53 +08:00
|
|
|
|
2017-01-25 23:16:10 +08:00
|
|
|
# MySQLdb 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.
|
2006-05-02 09:31:56 +08:00
|
|
|
django_conversions = conversions.copy()
|
|
|
|
django_conversions.update({
|
2013-09-17 00:52:05 +08:00
|
|
|
FIELD_TYPE.TIME: backend_utils.typecast_time,
|
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
|
2016-09-30 20:58:59 +08:00
|
|
|
# versions like 5.0.24 and 5.0.24a as the same).
|
2006-09-27 10:42:31 +08:00
|
|
|
server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class CursorWrapper:
|
2008-08-29 12:30:07 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
A thin wrapper around MySQLdb's normal cursor class that catches particular
|
|
|
|
exception instances and reraises them with the correct types.
|
2008-08-29 12:30:07 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Implemented as a wrapper, rather than a subclass, so that it isn't stuck
|
2008-08-29 12:30:07 +08:00
|
|
|
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:
|
2013-03-23 23:09:56 +08:00
|
|
|
# args is None means no string interpolation
|
2008-08-29 12:30:07 +08:00
|
|
|
return self.cursor.execute(query, args)
|
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.
|
2013-05-08 18:56:50 +08:00
|
|
|
if e.args[0] in self.codes_for_integrityerror:
|
2017-01-08 03:13:29 +08:00
|
|
|
raise utils.IntegrityError(*tuple(e.args))
|
Refactored database exceptions wrapping.
Squashed commit of the following:
commit 2181d833ed1a2e422494738dcef311164c4e097e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Wed Feb 27 14:28:39 2013 +0100
Fixed #15901 -- Wrapped all PEP-249 exceptions.
commit 5476a5d93c19aa2f928c497d39ce6e33f52694e2
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:26:52 2013 +0100
Added PEP 3134 exception chaining.
Thanks Jacob Kaplan-Moss for the suggestion.
commit 9365fad0a650328002fb424457d675a273c95802
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:13:49 2013 +0100
Improved API for wrapping database errors.
Thanks Alex Gaynor for the proposal.
commit 1b463b765f2826f73a8d9266795cd5da4f8d5e9e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 15:00:39 2013 +0100
Removed redundant exception wrapping.
This is now taken care of by the cursor wrapper.
commit 524bc7345a724bf526bdd2dd1bcf5ede67d6bb5c
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:55:10 2013 +0100
Wrapped database exceptions in the base backend.
This covers the most common PEP-249 APIs:
- Connection APIs: close(), commit(), rollback(), cursor()
- Cursor APIs: callproc(), close(), execute(), executemany(),
fetchone(), fetchmany(), fetchall(), nextset().
Fixed #19920.
commit a66746bb5f0839f35543222787fce3b6a0d0a3ea
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:53:34 2013 +0100
Added a wrap_database_exception context manager and decorator.
It re-throws backend-specific exceptions using Django's common wrappers.
2013-02-26 21:53:34 +08:00
|
|
|
raise
|
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.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.
|
2013-05-08 18:56:50 +08:00
|
|
|
if e.args[0] in self.codes_for_integrityerror:
|
2017-01-08 03:13:29 +08:00
|
|
|
raise utils.IntegrityError(*tuple(e.args))
|
Refactored database exceptions wrapping.
Squashed commit of the following:
commit 2181d833ed1a2e422494738dcef311164c4e097e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Wed Feb 27 14:28:39 2013 +0100
Fixed #15901 -- Wrapped all PEP-249 exceptions.
commit 5476a5d93c19aa2f928c497d39ce6e33f52694e2
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:26:52 2013 +0100
Added PEP 3134 exception chaining.
Thanks Jacob Kaplan-Moss for the suggestion.
commit 9365fad0a650328002fb424457d675a273c95802
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:13:49 2013 +0100
Improved API for wrapping database errors.
Thanks Alex Gaynor for the proposal.
commit 1b463b765f2826f73a8d9266795cd5da4f8d5e9e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 15:00:39 2013 +0100
Removed redundant exception wrapping.
This is now taken care of by the cursor wrapper.
commit 524bc7345a724bf526bdd2dd1bcf5ede67d6bb5c
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:55:10 2013 +0100
Wrapped database exceptions in the base backend.
This covers the most common PEP-249 APIs:
- Connection APIs: close(), commit(), rollback(), cursor()
- Cursor APIs: callproc(), close(), execute(), executemany(),
fetchone(), fetchmany(), fetchall(), nextset().
Fixed #19920.
commit a66746bb5f0839f35543222787fce3b6a0d0a3ea
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:53:34 2013 +0100
Added a wrap_database_exception context manager and decorator.
It re-throws backend-specific exceptions using Django's common wrappers.
2013-02-26 21:53:34 +08:00
|
|
|
raise
|
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)
|
|
|
|
|
2014-02-03 05:38:28 +08:00
|
|
|
def __enter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, type, value, traceback):
|
2017-01-19 18:00:41 +08:00
|
|
|
# Close instead of passing through to avoid backend-specific behavior
|
|
|
|
# (#17671).
|
2014-02-03 05:38:28 +08:00
|
|
|
self.close()
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2007-08-20 05:30:57 +08:00
|
|
|
class DatabaseWrapper(BaseDatabaseWrapper):
|
2010-10-11 20:55:17 +08:00
|
|
|
vendor = 'mysql'
|
2017-05-23 21:09:35 +08:00
|
|
|
display_name = 'MySQL'
|
2014-12-30 04:14:40 +08:00
|
|
|
# This dictionary maps Field objects to their associated MySQL column
|
|
|
|
# types, as strings. Column-type strings can contain format strings; they'll
|
|
|
|
# be interpolated against the values of Field.__dict__ before being output.
|
|
|
|
# If a column type is set to None, it won't be included in the output.
|
|
|
|
_data_types = {
|
|
|
|
'AutoField': 'integer AUTO_INCREMENT',
|
2015-07-02 16:43:15 +08:00
|
|
|
'BigAutoField': 'bigint AUTO_INCREMENT',
|
2014-12-30 04:14:40 +08:00
|
|
|
'BinaryField': 'longblob',
|
|
|
|
'BooleanField': 'bool',
|
|
|
|
'CharField': 'varchar(%(max_length)s)',
|
|
|
|
'DateField': 'date',
|
|
|
|
'DateTimeField': 'datetime',
|
|
|
|
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
|
|
|
|
'DurationField': 'bigint',
|
|
|
|
'FileField': 'varchar(%(max_length)s)',
|
|
|
|
'FilePathField': 'varchar(%(max_length)s)',
|
|
|
|
'FloatField': 'double precision',
|
|
|
|
'IntegerField': 'integer',
|
|
|
|
'BigIntegerField': 'bigint',
|
|
|
|
'IPAddressField': 'char(15)',
|
|
|
|
'GenericIPAddressField': 'char(39)',
|
|
|
|
'NullBooleanField': 'bool',
|
|
|
|
'OneToOneField': 'integer',
|
|
|
|
'PositiveIntegerField': 'integer UNSIGNED',
|
|
|
|
'PositiveSmallIntegerField': 'smallint UNSIGNED',
|
|
|
|
'SlugField': 'varchar(%(max_length)s)',
|
|
|
|
'SmallIntegerField': 'smallint',
|
|
|
|
'TextField': 'longtext',
|
|
|
|
'TimeField': 'time',
|
|
|
|
'UUIDField': 'char(32)',
|
|
|
|
}
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def data_types(self):
|
|
|
|
if self.features.supports_microsecond_precision:
|
|
|
|
return dict(self._data_types, DateTimeField='datetime(6)', TimeField='time(6)')
|
|
|
|
else:
|
|
|
|
return self._data_types
|
|
|
|
|
2017-05-23 23:02:40 +08:00
|
|
|
# For these columns, MySQL doesn't:
|
|
|
|
# - accept default values and implicitly treats these columns as nullable
|
|
|
|
# - support a database index
|
|
|
|
_limited_data_types = (
|
|
|
|
'tinyblob', 'blob', 'mediumblob', 'longblob', 'tinytext', 'text',
|
|
|
|
'mediumtext', 'longtext', 'json',
|
|
|
|
)
|
|
|
|
|
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
|
|
|
|
2014-09-27 18:41:54 +08:00
|
|
|
# The patterns below are used to generate SQL pattern lookup clauses when
|
|
|
|
# the right-hand side of the lookup isn't a raw string (it might be an expression
|
|
|
|
# or the result of a bilateral transformation).
|
|
|
|
# In those cases, special characters for LIKE operators (e.g. \, *, _) should be
|
|
|
|
# escaped on database side.
|
|
|
|
#
|
|
|
|
# Note: we use str.format() here for readability as '%' is used as a wildcard for
|
|
|
|
# the LIKE operator.
|
|
|
|
pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\\', '\\\\'), '%%', '\%%'), '_', '\_')"
|
|
|
|
pattern_ops = {
|
|
|
|
'contains': "LIKE BINARY CONCAT('%%', {}, '%%')",
|
|
|
|
'icontains': "LIKE CONCAT('%%', {}, '%%')",
|
|
|
|
'startswith': "LIKE BINARY CONCAT({}, '%%')",
|
|
|
|
'istartswith': "LIKE CONCAT({}, '%%')",
|
|
|
|
'endswith': "LIKE BINARY CONCAT('%%', {})",
|
|
|
|
'iendswith': "LIKE CONCAT('%%', {})",
|
|
|
|
}
|
|
|
|
|
2017-01-18 00:16:15 +08:00
|
|
|
isolation_levels = {
|
|
|
|
'read uncommitted',
|
|
|
|
'read committed',
|
|
|
|
'repeatable read',
|
|
|
|
'serializable',
|
|
|
|
}
|
|
|
|
|
Refactored database exceptions wrapping.
Squashed commit of the following:
commit 2181d833ed1a2e422494738dcef311164c4e097e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Wed Feb 27 14:28:39 2013 +0100
Fixed #15901 -- Wrapped all PEP-249 exceptions.
commit 5476a5d93c19aa2f928c497d39ce6e33f52694e2
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:26:52 2013 +0100
Added PEP 3134 exception chaining.
Thanks Jacob Kaplan-Moss for the suggestion.
commit 9365fad0a650328002fb424457d675a273c95802
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 17:13:49 2013 +0100
Improved API for wrapping database errors.
Thanks Alex Gaynor for the proposal.
commit 1b463b765f2826f73a8d9266795cd5da4f8d5e9e
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 15:00:39 2013 +0100
Removed redundant exception wrapping.
This is now taken care of by the cursor wrapper.
commit 524bc7345a724bf526bdd2dd1bcf5ede67d6bb5c
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:55:10 2013 +0100
Wrapped database exceptions in the base backend.
This covers the most common PEP-249 APIs:
- Connection APIs: close(), commit(), rollback(), cursor()
- Cursor APIs: callproc(), close(), execute(), executemany(),
fetchone(), fetchmany(), fetchall(), nextset().
Fixed #19920.
commit a66746bb5f0839f35543222787fce3b6a0d0a3ea
Author: Aymeric Augustin <aymeric.augustin@m4x.org>
Date: Tue Feb 26 14:53:34 2013 +0100
Added a wrap_database_exception context manager and decorator.
It re-throws backend-specific exceptions using Django's common wrappers.
2013-02-26 21:53:34 +08:00
|
|
|
Database = Database
|
2014-09-26 01:59:03 +08:00
|
|
|
SchemaEditorClass = DatabaseSchemaEditor
|
2016-09-09 04:33:36 +08:00
|
|
|
# Classes instantiated in __init__().
|
|
|
|
client_class = DatabaseClient
|
|
|
|
creation_class = DatabaseCreation
|
|
|
|
features_class = DatabaseFeatures
|
|
|
|
introspection_class = DatabaseIntrospection
|
|
|
|
ops_class = DatabaseOperations
|
|
|
|
validation_class = DatabaseValidation
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2012-11-27 04:42:27 +08:00
|
|
|
def get_connection_params(self):
|
|
|
|
kwargs = {
|
|
|
|
'conv': django_conversions,
|
|
|
|
'charset': 'utf8',
|
|
|
|
}
|
|
|
|
settings_dict = self.settings_dict
|
|
|
|
if settings_dict['USER']:
|
|
|
|
kwargs['user'] = settings_dict['USER']
|
|
|
|
if settings_dict['NAME']:
|
|
|
|
kwargs['db'] = settings_dict['NAME']
|
|
|
|
if settings_dict['PASSWORD']:
|
2017-01-12 06:17:25 +08:00
|
|
|
kwargs['passwd'] = settings_dict['PASSWORD']
|
2012-11-27 04:42:27 +08:00
|
|
|
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'])
|
|
|
|
# We need the number of potentially affected rows after an
|
|
|
|
# "UPDATE", not the number of changed rows.
|
|
|
|
kwargs['client_flag'] = CLIENT.FOUND_ROWS
|
2017-01-18 00:16:15 +08:00
|
|
|
# Validate the transaction isolation level, if specified.
|
|
|
|
options = settings_dict['OPTIONS'].copy()
|
2017-02-02 04:34:17 +08:00
|
|
|
isolation_level = options.pop('isolation_level', 'read committed')
|
2017-01-18 00:16:15 +08:00
|
|
|
if isolation_level:
|
|
|
|
isolation_level = isolation_level.lower()
|
|
|
|
if isolation_level not in self.isolation_levels:
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"Invalid transaction isolation level '%s' specified.\n"
|
|
|
|
"Use one of %s, or None." % (
|
|
|
|
isolation_level,
|
|
|
|
', '.join("'%s'" % s for s in sorted(self.isolation_levels))
|
|
|
|
))
|
|
|
|
# The variable assignment form of setting transaction isolation
|
|
|
|
# levels will be used, e.g. "set tx_isolation='repeatable-read'".
|
|
|
|
isolation_level = isolation_level.replace(' ', '-')
|
|
|
|
self.isolation_level = isolation_level
|
|
|
|
kwargs.update(options)
|
2012-11-27 04:42:27 +08:00
|
|
|
return kwargs
|
|
|
|
|
|
|
|
def get_new_connection(self, conn_params):
|
2017-01-23 23:36:48 +08:00
|
|
|
return Database.connect(**conn_params)
|
2012-11-27 04:42:27 +08:00
|
|
|
|
|
|
|
def init_connection_state(self):
|
2017-01-18 00:16:15 +08:00
|
|
|
assignments = []
|
2015-12-15 10:19:40 +08:00
|
|
|
if self.features.is_sql_auto_is_null_enabled:
|
2017-01-18 00:16:15 +08:00
|
|
|
# SQL_AUTO_IS_NULL controls whether an AUTO_INCREMENT column on
|
|
|
|
# a recently inserted row will return when the field is tested
|
|
|
|
# for NULL. Disabling this brings this aspect of MySQL in line
|
|
|
|
# with SQL standards.
|
|
|
|
assignments.append('SQL_AUTO_IS_NULL = 0')
|
|
|
|
|
|
|
|
if self.isolation_level:
|
|
|
|
assignments.append("TX_ISOLATION = '%s'" % self.isolation_level)
|
|
|
|
|
|
|
|
if assignments:
|
2015-12-15 10:19:40 +08:00
|
|
|
with self.cursor() as cursor:
|
2017-01-18 00:16:15 +08:00
|
|
|
cursor.execute('SET ' + ', '.join(assignments))
|
2012-11-27 04:42:27 +08:00
|
|
|
|
2016-06-04 06:31:21 +08:00
|
|
|
def create_cursor(self, name=None):
|
2011-09-11 02:58:30 +08:00
|
|
|
cursor = self.connection.cursor()
|
|
|
|
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
|
|
|
|
2013-03-02 20:47:46 +08:00
|
|
|
def _set_autocommit(self, autocommit):
|
2014-03-24 06:09:26 +08:00
|
|
|
with self.wrap_database_errors:
|
|
|
|
self.connection.autocommit(autocommit)
|
2011-08-07 08:43:26 +08:00
|
|
|
|
|
|
|
def disable_constraint_checking(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Disable foreign key checks, primarily for use in adding rows with
|
|
|
|
forward references. Always return True to indicate constraint checks
|
|
|
|
need to be re-enabled.
|
2011-08-07 08:43:26 +08:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2013-09-23 04:14:17 +08:00
|
|
|
# Override needs_rollback in case constraint_checks_disabled is
|
|
|
|
# nested inside transaction.atomic.
|
|
|
|
self.needs_rollback, needs_rollback = False, self.needs_rollback
|
|
|
|
try:
|
|
|
|
self.cursor().execute('SET foreign_key_checks=1')
|
|
|
|
finally:
|
|
|
|
self.needs_rollback = needs_rollback
|
2011-08-07 08:43:26 +08:00
|
|
|
|
|
|
|
def check_constraints(self, table_names=None):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Check each table name in `table_names` for rows with invalid foreign
|
2014-09-04 20:15:09 +08:00
|
|
|
key references. This method is 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.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Raise an IntegrityError on the first invalid foreign key reference
|
|
|
|
encountered (if any) and provide detailed information about the
|
2014-09-04 20:15:09 +08:00
|
|
|
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")
|
2011-08-07 08:43:26 +08:00
|
|
|
"""
|
|
|
|
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:
|
2016-03-29 06:33:29 +08:00
|
|
|
cursor.execute(
|
|
|
|
"""
|
2011-08-07 08:43:26 +08:00
|
|
|
SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
|
|
|
|
LEFT JOIN `%s` as REFERRED
|
|
|
|
ON (REFERRING.`%s` = REFERRED.`%s`)
|
2016-03-29 06:33:29 +08:00
|
|
|
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,
|
|
|
|
)
|
|
|
|
)
|
2011-08-07 08:43:26 +08:00
|
|
|
for bad_row in cursor.fetchall():
|
2016-03-29 06:33:29 +08:00
|
|
|
raise utils.IntegrityError(
|
|
|
|
"The row in table '%s' with primary key '%s' has an invalid "
|
2011-08-07 08:43:26 +08:00
|
|
|
"foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
|
2016-03-29 06:33:29 +08:00
|
|
|
% (
|
|
|
|
table_name, bad_row[0], table_name, column_name,
|
|
|
|
bad_row[1], referenced_table_name, referenced_column_name,
|
|
|
|
)
|
|
|
|
)
|
2012-08-18 19:29:31 +08:00
|
|
|
|
2013-03-02 19:12:51 +08:00
|
|
|
def is_usable(self):
|
|
|
|
try:
|
|
|
|
self.connection.ping()
|
2014-04-10 04:41:33 +08:00
|
|
|
except Database.Error:
|
2013-03-02 19:12:51 +08:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def mysql_version(self):
|
2016-07-07 21:13:56 +08:00
|
|
|
with self.temporary_connection() as cursor:
|
|
|
|
cursor.execute('SELECT VERSION()')
|
|
|
|
server_info = cursor.fetchone()[0]
|
2013-03-02 19:12:51 +08:00
|
|
|
match = server_version_re.match(server_info)
|
|
|
|
if not match:
|
|
|
|
raise Exception('Unable to determine MySQL version from version string %r' % server_info)
|
2013-08-30 00:09:35 +08:00
|
|
|
return tuple(int(x) for x in match.groups())
|