base.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. """
  2. MySQL database backend for Django.
  3. Requires MySQLdb: http://sourceforge.net/projects/mysql-python
  4. """
  5. from __future__ import unicode_literals
  6. import datetime
  7. import re
  8. import sys
  9. import warnings
  10. try:
  11. import MySQLdb as Database
  12. except ImportError as e:
  13. from django.core.exceptions import ImproperlyConfigured
  14. raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
  15. # We want version (1, 2, 1, 'final', 2) or later. We can't just use
  16. # lexicographic ordering in this check because then (1, 2, 1, 'gamma')
  17. # inadvertently passes the version test.
  18. version = Database.version_info
  19. if (version < (1, 2, 1) or (version[:3] == (1, 2, 1) and
  20. (len(version) < 5 or version[3] != 'final' or version[4] < 2))):
  21. from django.core.exceptions import ImproperlyConfigured
  22. raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__)
  23. from MySQLdb.converters import conversions, Thing2Literal
  24. from MySQLdb.constants import FIELD_TYPE, CLIENT
  25. try:
  26. import pytz
  27. except ImportError:
  28. pytz = None
  29. from django.conf import settings
  30. from django.db import utils
  31. from django.db.backends import (utils as backend_utils, BaseDatabaseFeatures,
  32. BaseDatabaseOperations, BaseDatabaseWrapper)
  33. from django.db.backends.mysql.client import DatabaseClient
  34. from django.db.backends.mysql.creation import DatabaseCreation
  35. from django.db.backends.mysql.introspection import DatabaseIntrospection
  36. from django.db.backends.mysql.validation import DatabaseValidation
  37. from django.utils.encoding import force_str, force_text
  38. from django.db.backends.mysql.schema import DatabaseSchemaEditor
  39. from django.utils.functional import cached_property
  40. from django.utils.safestring import SafeBytes, SafeText
  41. from django.utils import six
  42. from django.utils import timezone
  43. # Raise exceptions for database warnings if DEBUG is on
  44. if settings.DEBUG:
  45. warnings.filterwarnings("error", category=Database.Warning)
  46. DatabaseError = Database.DatabaseError
  47. IntegrityError = Database.IntegrityError
  48. # It's impossible to import datetime_or_None directly from MySQLdb.times
  49. parse_datetime = conversions[FIELD_TYPE.DATETIME]
  50. def parse_datetime_with_timezone_support(value):
  51. dt = parse_datetime(value)
  52. # Confirm that dt is naive before overwriting its tzinfo.
  53. if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
  54. dt = dt.replace(tzinfo=timezone.utc)
  55. return dt
  56. def adapt_datetime_with_timezone_support(value, conv):
  57. # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
  58. if settings.USE_TZ:
  59. if timezone.is_naive(value):
  60. warnings.warn("MySQL received a naive datetime (%s)"
  61. " while time zone support is active." % value,
  62. RuntimeWarning)
  63. default_timezone = timezone.get_default_timezone()
  64. value = timezone.make_aware(value, default_timezone)
  65. value = value.astimezone(timezone.utc).replace(tzinfo=None)
  66. return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S"), conv)
  67. # MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
  68. # timedelta in terms of actual behavior as they are signed and include days --
  69. # and Django expects time, so we still need to override that. We also need to
  70. # add special handling for SafeText and SafeBytes as MySQLdb's type
  71. # checking is too tight to catch those (see Django ticket #6052).
  72. # Finally, MySQLdb always returns naive datetime objects. However, when
  73. # timezone support is active, Django expects timezone-aware datetime objects.
  74. django_conversions = conversions.copy()
  75. django_conversions.update({
  76. FIELD_TYPE.TIME: backend_utils.typecast_time,
  77. FIELD_TYPE.DECIMAL: backend_utils.typecast_decimal,
  78. FIELD_TYPE.NEWDECIMAL: backend_utils.typecast_decimal,
  79. FIELD_TYPE.DATETIME: parse_datetime_with_timezone_support,
  80. datetime.datetime: adapt_datetime_with_timezone_support,
  81. })
  82. # This should match the numerical portion of the version numbers (we can treat
  83. # versions like 5.0.24 and 5.0.24a as the same). Based on the list of version
  84. # at http://dev.mysql.com/doc/refman/4.1/en/news.html and
  85. # http://dev.mysql.com/doc/refman/5.0/en/news.html .
  86. server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
  87. # MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
  88. # MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
  89. # point is to raise Warnings as exceptions, this can be done with the Python
  90. # warning module, and this is setup when the connection is created, and the
  91. # standard backend_utils.CursorDebugWrapper can be used. Also, using sql_mode
  92. # TRADITIONAL will automatically cause most warnings to be treated as errors.
  93. class CursorWrapper(object):
  94. """
  95. A thin wrapper around MySQLdb's normal cursor class so that we can catch
  96. particular exception instances and reraise them with the right types.
  97. Implemented as a wrapper, rather than a subclass, so that we aren't stuck
  98. to the particular underlying representation returned by Connection.cursor().
  99. """
  100. codes_for_integrityerror = (1048,)
  101. def __init__(self, cursor):
  102. self.cursor = cursor
  103. def execute(self, query, args=None):
  104. try:
  105. # args is None means no string interpolation
  106. return self.cursor.execute(query, args)
  107. except Database.OperationalError as e:
  108. # Map some error codes to IntegrityError, since they seem to be
  109. # misclassified and Django would prefer the more logical place.
  110. if e.args[0] in self.codes_for_integrityerror:
  111. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
  112. raise
  113. def executemany(self, query, args):
  114. try:
  115. return self.cursor.executemany(query, args)
  116. except Database.OperationalError as e:
  117. # Map some error codes to IntegrityError, since they seem to be
  118. # misclassified and Django would prefer the more logical place.
  119. if e.args[0] in self.codes_for_integrityerror:
  120. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
  121. raise
  122. def __getattr__(self, attr):
  123. if attr in self.__dict__:
  124. return self.__dict__[attr]
  125. else:
  126. return getattr(self.cursor, attr)
  127. def __iter__(self):
  128. return iter(self.cursor)
  129. def __enter__(self):
  130. return self
  131. def __exit__(self, type, value, traceback):
  132. # Ticket #17671 - Close instead of passing thru to avoid backend
  133. # specific behavior.
  134. self.close()
  135. class DatabaseFeatures(BaseDatabaseFeatures):
  136. empty_fetchmany_value = ()
  137. update_can_self_select = False
  138. allows_group_by_pk = True
  139. related_fields_match_type = True
  140. allow_sliced_subqueries = False
  141. has_bulk_insert = True
  142. has_select_for_update = True
  143. has_select_for_update_nowait = False
  144. supports_forward_references = False
  145. supports_long_model_names = False
  146. # XXX MySQL DB-API drivers currently fail on binary data on Python 3.
  147. supports_binary_field = six.PY2
  148. supports_microsecond_precision = False
  149. supports_regex_backreferencing = False
  150. supports_date_lookup_using_string = False
  151. can_introspect_binary_field = False
  152. can_introspect_boolean_field = False
  153. supports_timezones = False
  154. requires_explicit_null_ordering_when_grouping = True
  155. allows_auto_pk_0 = False
  156. uses_savepoints = True
  157. atomic_transactions = False
  158. supports_column_check_constraints = False
  159. def __init__(self, connection):
  160. super(DatabaseFeatures, self).__init__(connection)
  161. @cached_property
  162. def _mysql_storage_engine(self):
  163. "Internal method used in Django tests. Don't rely on this from your code"
  164. with self.connection.cursor() as cursor:
  165. cursor.execute('CREATE TABLE INTROSPECT_TEST (X INT)')
  166. # This command is MySQL specific; the second column
  167. # will tell you the default table type of the created
  168. # table. Since all Django's test tables will have the same
  169. # table type, that's enough to evaluate the feature.
  170. cursor.execute("SHOW TABLE STATUS WHERE Name='INTROSPECT_TEST'")
  171. result = cursor.fetchone()
  172. cursor.execute('DROP TABLE INTROSPECT_TEST')
  173. return result[1]
  174. @cached_property
  175. def can_introspect_foreign_keys(self):
  176. "Confirm support for introspected foreign keys"
  177. return self._mysql_storage_engine != 'MyISAM'
  178. @cached_property
  179. def has_zoneinfo_database(self):
  180. # MySQL accepts full time zones names (eg. Africa/Nairobi) but rejects
  181. # abbreviations (eg. EAT). When pytz isn't installed and the current
  182. # time zone is LocalTimezone (the only sensible value in this
  183. # context), the current time zone name will be an abbreviation. As a
  184. # consequence, MySQL cannot perform time zone conversions reliably.
  185. if pytz is None:
  186. return False
  187. # Test if the time zone definitions are installed.
  188. with self.connection.cursor() as cursor:
  189. cursor.execute("SELECT 1 FROM mysql.time_zone LIMIT 1")
  190. return cursor.fetchone() is not None
  191. class DatabaseOperations(BaseDatabaseOperations):
  192. compiler_module = "django.db.backends.mysql.compiler"
  193. # MySQL stores positive fields as UNSIGNED ints.
  194. integer_field_ranges = dict(BaseDatabaseOperations.integer_field_ranges,
  195. PositiveSmallIntegerField=(0, 4294967295),
  196. PositiveIntegerField=(0, 18446744073709551615),
  197. )
  198. def date_extract_sql(self, lookup_type, field_name):
  199. # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
  200. if lookup_type == 'week_day':
  201. # DAYOFWEEK() returns an integer, 1-7, Sunday=1.
  202. # Note: WEEKDAY() returns 0-6, Monday=0.
  203. return "DAYOFWEEK(%s)" % field_name
  204. else:
  205. return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
  206. def date_trunc_sql(self, lookup_type, field_name):
  207. fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
  208. format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
  209. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
  210. try:
  211. i = fields.index(lookup_type) + 1
  212. except ValueError:
  213. sql = field_name
  214. else:
  215. format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
  216. sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
  217. return sql
  218. def datetime_extract_sql(self, lookup_type, field_name, tzname):
  219. if settings.USE_TZ:
  220. field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name
  221. params = [tzname]
  222. else:
  223. params = []
  224. # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
  225. if lookup_type == 'week_day':
  226. # DAYOFWEEK() returns an integer, 1-7, Sunday=1.
  227. # Note: WEEKDAY() returns 0-6, Monday=0.
  228. sql = "DAYOFWEEK(%s)" % field_name
  229. else:
  230. sql = "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
  231. return sql, params
  232. def datetime_trunc_sql(self, lookup_type, field_name, tzname):
  233. if settings.USE_TZ:
  234. field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name
  235. params = [tzname]
  236. else:
  237. params = []
  238. fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
  239. format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
  240. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
  241. try:
  242. i = fields.index(lookup_type) + 1
  243. except ValueError:
  244. sql = field_name
  245. else:
  246. format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
  247. sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
  248. return sql, params
  249. def date_interval_sql(self, sql, connector, timedelta):
  250. return "(%s %s INTERVAL '%d 0:0:%d:%d' DAY_MICROSECOND)" % (sql, connector,
  251. timedelta.days, timedelta.seconds, timedelta.microseconds)
  252. def drop_foreignkey_sql(self):
  253. return "DROP FOREIGN KEY"
  254. def force_no_ordering(self):
  255. """
  256. "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
  257. columns. If no ordering would otherwise be applied, we don't want any
  258. implicit sorting going on.
  259. """
  260. return ["NULL"]
  261. def fulltext_search_sql(self, field_name):
  262. return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name
  263. def last_executed_query(self, cursor, sql, params):
  264. # With MySQLdb, cursor objects have an (undocumented) "_last_executed"
  265. # attribute where the exact query sent to the database is saved.
  266. # See MySQLdb/cursors.py in the source distribution.
  267. return force_text(getattr(cursor, '_last_executed', None), errors='replace')
  268. def no_limit_value(self):
  269. # 2**64 - 1, as recommended by the MySQL documentation
  270. return 18446744073709551615
  271. def quote_name(self, name):
  272. if name.startswith("`") and name.endswith("`"):
  273. return name # Quoting once is enough.
  274. return "`%s`" % name
  275. def random_function_sql(self):
  276. return 'RAND()'
  277. def sql_flush(self, style, tables, sequences, allow_cascade=False):
  278. # NB: The generated SQL below is specific to MySQL
  279. # 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements
  280. # to clear all tables of all data
  281. if tables:
  282. sql = ['SET FOREIGN_KEY_CHECKS = 0;']
  283. for table in tables:
  284. sql.append('%s %s;' % (
  285. style.SQL_KEYWORD('TRUNCATE'),
  286. style.SQL_FIELD(self.quote_name(table)),
  287. ))
  288. sql.append('SET FOREIGN_KEY_CHECKS = 1;')
  289. sql.extend(self.sequence_reset_by_name_sql(style, sequences))
  290. return sql
  291. else:
  292. return []
  293. def sequence_reset_by_name_sql(self, style, sequences):
  294. # Truncate already resets the AUTO_INCREMENT field from
  295. # MySQL version 5.0.13 onwards. Refs #16961.
  296. if self.connection.mysql_version < (5, 0, 13):
  297. return [
  298. "%s %s %s %s %s;" % (
  299. style.SQL_KEYWORD('ALTER'),
  300. style.SQL_KEYWORD('TABLE'),
  301. style.SQL_TABLE(self.quote_name(sequence['table'])),
  302. style.SQL_KEYWORD('AUTO_INCREMENT'),
  303. style.SQL_FIELD('= 1'),
  304. ) for sequence in sequences
  305. ]
  306. else:
  307. return []
  308. def validate_autopk_value(self, value):
  309. # MySQLism: zero in AUTO_INCREMENT field does not work. Refs #17653.
  310. if value == 0:
  311. raise ValueError('The database backend does not accept 0 as a '
  312. 'value for AutoField.')
  313. return value
  314. def value_to_db_datetime(self, value):
  315. if value is None:
  316. return None
  317. # MySQL doesn't support tz-aware datetimes
  318. if timezone.is_aware(value):
  319. if settings.USE_TZ:
  320. value = value.astimezone(timezone.utc).replace(tzinfo=None)
  321. else:
  322. raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")
  323. # MySQL doesn't support microseconds
  324. return six.text_type(value.replace(microsecond=0))
  325. def value_to_db_time(self, value):
  326. if value is None:
  327. return None
  328. # MySQL doesn't support tz-aware times
  329. if timezone.is_aware(value):
  330. raise ValueError("MySQL backend does not support timezone-aware times.")
  331. # MySQL doesn't support microseconds
  332. return six.text_type(value.replace(microsecond=0))
  333. def year_lookup_bounds_for_datetime_field(self, value):
  334. # Again, no microseconds
  335. first, second = super(DatabaseOperations, self).year_lookup_bounds_for_datetime_field(value)
  336. return [first.replace(microsecond=0), second.replace(microsecond=0)]
  337. def max_name_length(self):
  338. return 64
  339. def bulk_insert_sql(self, fields, num_values):
  340. items_sql = "(%s)" % ", ".join(["%s"] * len(fields))
  341. return "VALUES " + ", ".join([items_sql] * num_values)
  342. def combine_expression(self, connector, sub_expressions):
  343. """
  344. MySQL requires special cases for ^ operators in query expressions
  345. """
  346. if connector == '^':
  347. return 'POW(%s)' % ','.join(sub_expressions)
  348. return super(DatabaseOperations, self).combine_expression(connector, sub_expressions)
  349. class DatabaseWrapper(BaseDatabaseWrapper):
  350. vendor = 'mysql'
  351. operators = {
  352. 'exact': '= %s',
  353. 'iexact': 'LIKE %s',
  354. 'contains': 'LIKE BINARY %s',
  355. 'icontains': 'LIKE %s',
  356. 'regex': 'REGEXP BINARY %s',
  357. 'iregex': 'REGEXP %s',
  358. 'gt': '> %s',
  359. 'gte': '>= %s',
  360. 'lt': '< %s',
  361. 'lte': '<= %s',
  362. 'startswith': 'LIKE BINARY %s',
  363. 'endswith': 'LIKE BINARY %s',
  364. 'istartswith': 'LIKE %s',
  365. 'iendswith': 'LIKE %s',
  366. }
  367. Database = Database
  368. def __init__(self, *args, **kwargs):
  369. super(DatabaseWrapper, self).__init__(*args, **kwargs)
  370. self.features = DatabaseFeatures(self)
  371. self.ops = DatabaseOperations(self)
  372. self.client = DatabaseClient(self)
  373. self.creation = DatabaseCreation(self)
  374. self.introspection = DatabaseIntrospection(self)
  375. self.validation = DatabaseValidation(self)
  376. def get_connection_params(self):
  377. kwargs = {
  378. 'conv': django_conversions,
  379. 'charset': 'utf8',
  380. }
  381. if six.PY2:
  382. kwargs['use_unicode'] = True
  383. settings_dict = self.settings_dict
  384. if settings_dict['USER']:
  385. kwargs['user'] = settings_dict['USER']
  386. if settings_dict['NAME']:
  387. kwargs['db'] = settings_dict['NAME']
  388. if settings_dict['PASSWORD']:
  389. kwargs['passwd'] = force_str(settings_dict['PASSWORD'])
  390. if settings_dict['HOST'].startswith('/'):
  391. kwargs['unix_socket'] = settings_dict['HOST']
  392. elif settings_dict['HOST']:
  393. kwargs['host'] = settings_dict['HOST']
  394. if settings_dict['PORT']:
  395. kwargs['port'] = int(settings_dict['PORT'])
  396. # We need the number of potentially affected rows after an
  397. # "UPDATE", not the number of changed rows.
  398. kwargs['client_flag'] = CLIENT.FOUND_ROWS
  399. kwargs.update(settings_dict['OPTIONS'])
  400. return kwargs
  401. def get_new_connection(self, conn_params):
  402. conn = Database.connect(**conn_params)
  403. conn.encoders[SafeText] = conn.encoders[six.text_type]
  404. conn.encoders[SafeBytes] = conn.encoders[bytes]
  405. return conn
  406. def init_connection_state(self):
  407. with self.cursor() as cursor:
  408. # SQL_AUTO_IS_NULL in MySQL controls whether an AUTO_INCREMENT column
  409. # on a recently-inserted row will return when the field is tested for
  410. # NULL. Disabling this value brings this aspect of MySQL in line with
  411. # SQL standards.
  412. cursor.execute('SET SQL_AUTO_IS_NULL = 0')
  413. def create_cursor(self):
  414. cursor = self.connection.cursor()
  415. return CursorWrapper(cursor)
  416. def _rollback(self):
  417. try:
  418. BaseDatabaseWrapper._rollback(self)
  419. except Database.NotSupportedError:
  420. pass
  421. def _set_autocommit(self, autocommit):
  422. with self.wrap_database_errors:
  423. self.connection.autocommit(autocommit)
  424. def disable_constraint_checking(self):
  425. """
  426. Disables foreign key checks, primarily for use in adding rows with forward references. Always returns True,
  427. to indicate constraint checks need to be re-enabled.
  428. """
  429. self.cursor().execute('SET foreign_key_checks=0')
  430. return True
  431. def enable_constraint_checking(self):
  432. """
  433. Re-enable foreign key checks after they have been disabled.
  434. """
  435. # Override needs_rollback in case constraint_checks_disabled is
  436. # nested inside transaction.atomic.
  437. self.needs_rollback, needs_rollback = False, self.needs_rollback
  438. try:
  439. self.cursor().execute('SET foreign_key_checks=1')
  440. finally:
  441. self.needs_rollback = needs_rollback
  442. def check_constraints(self, table_names=None):
  443. """
  444. Checks each table name in `table_names` for rows with invalid foreign key references. This method is
  445. intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
  446. determine if rows with invalid references were entered while constraint checks were off.
  447. Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides
  448. detailed information about the invalid reference in the error message.
  449. Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS
  450. ALL IMMEDIATE")
  451. """
  452. cursor = self.cursor()
  453. if table_names is None:
  454. table_names = self.introspection.table_names(cursor)
  455. for table_name in table_names:
  456. primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
  457. if not primary_key_column_name:
  458. continue
  459. key_columns = self.introspection.get_key_columns(cursor, table_name)
  460. for column_name, referenced_table_name, referenced_column_name in key_columns:
  461. cursor.execute("""
  462. SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
  463. LEFT JOIN `%s` as REFERRED
  464. ON (REFERRING.`%s` = REFERRED.`%s`)
  465. WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
  466. % (primary_key_column_name, column_name, table_name, referenced_table_name,
  467. column_name, referenced_column_name, column_name, referenced_column_name))
  468. for bad_row in cursor.fetchall():
  469. raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
  470. "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
  471. % (table_name, bad_row[0],
  472. table_name, column_name, bad_row[1],
  473. referenced_table_name, referenced_column_name))
  474. def schema_editor(self, *args, **kwargs):
  475. "Returns a new instance of this backend's SchemaEditor"
  476. return DatabaseSchemaEditor(self, *args, **kwargs)
  477. def is_usable(self):
  478. try:
  479. self.connection.ping()
  480. except Database.Error:
  481. return False
  482. else:
  483. return True
  484. @cached_property
  485. def mysql_version(self):
  486. with self.temporary_connection():
  487. server_info = self.connection.get_server_info()
  488. match = server_version_re.match(server_info)
  489. if not match:
  490. raise Exception('Unable to determine MySQL version from version string %r' % server_info)
  491. return tuple(int(x) for x in match.groups())