PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/django/db/backends/mysql/base.py

https://gitlab.com/Guy1394/django
Python | 366 lines | 269 code | 31 blank | 66 comment | 27 complexity | 3ef4b04d6cf90414a0549ebfc6c8b52e MD5 | raw file
  1. """
  2. MySQL database backend for Django.
  3. Requires mysqlclient: https://pypi.python.org/pypi/mysqlclient/
  4. MySQLdb is supported for Python 2 only: http://sourceforge.net/projects/mysql-python
  5. """
  6. from __future__ import unicode_literals
  7. import datetime
  8. import re
  9. import sys
  10. import warnings
  11. from django.conf import settings
  12. from django.db import utils
  13. from django.db.backends import utils as backend_utils
  14. from django.db.backends.base.base import BaseDatabaseWrapper
  15. from django.utils import six, timezone
  16. from django.utils.deprecation import RemovedInDjango20Warning
  17. from django.utils.encoding import force_str
  18. from django.utils.functional import cached_property
  19. from django.utils.safestring import SafeBytes, SafeText
  20. try:
  21. import MySQLdb as Database
  22. except ImportError as e:
  23. from django.core.exceptions import ImproperlyConfigured
  24. raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
  25. from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip
  26. from MySQLdb.converters import Thing2Literal, conversions # isort:skip
  27. # Some of these import MySQLdb, so import them after checking if it's installed.
  28. from .client import DatabaseClient # isort:skip
  29. from .creation import DatabaseCreation # isort:skip
  30. from .features import DatabaseFeatures # isort:skip
  31. from .introspection import DatabaseIntrospection # isort:skip
  32. from .operations import DatabaseOperations # isort:skip
  33. from .schema import DatabaseSchemaEditor # isort:skip
  34. from .validation import DatabaseValidation # isort:skip
  35. # We want version (1, 2, 1, 'final', 2) or later. We can't just use
  36. # lexicographic ordering in this check because then (1, 2, 1, 'gamma')
  37. # inadvertently passes the version test.
  38. version = Database.version_info
  39. if (version < (1, 2, 1) or (version[:3] == (1, 2, 1) and
  40. (len(version) < 5 or version[3] != 'final' or version[4] < 2))):
  41. from django.core.exceptions import ImproperlyConfigured
  42. raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__)
  43. DatabaseError = Database.DatabaseError
  44. IntegrityError = Database.IntegrityError
  45. def adapt_datetime_warn_on_aware_datetime(value, conv):
  46. # Remove this function and rely on the default adapter in Django 2.0.
  47. if settings.USE_TZ and timezone.is_aware(value):
  48. warnings.warn(
  49. "The MySQL database adapter received an aware datetime (%s), "
  50. "probably from cursor.execute(). Update your code to pass a "
  51. "naive datetime in the database connection's time zone (UTC by "
  52. "default).", RemovedInDjango20Warning)
  53. # This doesn't account for the database connection's timezone,
  54. # which isn't known. (That's why this adapter is deprecated.)
  55. value = value.astimezone(timezone.utc).replace(tzinfo=None)
  56. return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)
  57. # MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
  58. # timedelta in terms of actual behavior as they are signed and include days --
  59. # and Django expects time, so we still need to override that. We also need to
  60. # add special handling for SafeText and SafeBytes as MySQLdb's type
  61. # checking is too tight to catch those (see Django ticket #6052).
  62. django_conversions = conversions.copy()
  63. django_conversions.update({
  64. FIELD_TYPE.TIME: backend_utils.typecast_time,
  65. FIELD_TYPE.DECIMAL: backend_utils.typecast_decimal,
  66. FIELD_TYPE.NEWDECIMAL: backend_utils.typecast_decimal,
  67. datetime.datetime: adapt_datetime_warn_on_aware_datetime,
  68. })
  69. # This should match the numerical portion of the version numbers (we can treat
  70. # versions like 5.0.24 and 5.0.24a as the same). Based on the list of version
  71. # at http://dev.mysql.com/doc/refman/4.1/en/news.html and
  72. # http://dev.mysql.com/doc/refman/5.0/en/news.html .
  73. server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
  74. # MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
  75. # MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
  76. # point is to raise Warnings as exceptions, this can be done with the Python
  77. # warning module, and this is setup when the connection is created, and the
  78. # standard backend_utils.CursorDebugWrapper can be used. Also, using sql_mode
  79. # TRADITIONAL will automatically cause most warnings to be treated as errors.
  80. class CursorWrapper(object):
  81. """
  82. A thin wrapper around MySQLdb's normal cursor class so that we can catch
  83. particular exception instances and reraise them with the right types.
  84. Implemented as a wrapper, rather than a subclass, so that we aren't stuck
  85. to the particular underlying representation returned by Connection.cursor().
  86. """
  87. codes_for_integrityerror = (1048,)
  88. def __init__(self, cursor):
  89. self.cursor = cursor
  90. def execute(self, query, args=None):
  91. try:
  92. # args is None means no string interpolation
  93. return self.cursor.execute(query, args)
  94. except Database.OperationalError as e:
  95. # Map some error codes to IntegrityError, since they seem to be
  96. # misclassified and Django would prefer the more logical place.
  97. if e.args[0] in self.codes_for_integrityerror:
  98. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
  99. raise
  100. def executemany(self, query, args):
  101. try:
  102. return self.cursor.executemany(query, args)
  103. except Database.OperationalError as e:
  104. # Map some error codes to IntegrityError, since they seem to be
  105. # misclassified and Django would prefer the more logical place.
  106. if e.args[0] in self.codes_for_integrityerror:
  107. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
  108. raise
  109. def __getattr__(self, attr):
  110. if attr in self.__dict__:
  111. return self.__dict__[attr]
  112. else:
  113. return getattr(self.cursor, attr)
  114. def __iter__(self):
  115. return iter(self.cursor)
  116. def __enter__(self):
  117. return self
  118. def __exit__(self, type, value, traceback):
  119. # Ticket #17671 - Close instead of passing thru to avoid backend
  120. # specific behavior.
  121. self.close()
  122. class DatabaseWrapper(BaseDatabaseWrapper):
  123. vendor = 'mysql'
  124. # This dictionary maps Field objects to their associated MySQL column
  125. # types, as strings. Column-type strings can contain format strings; they'll
  126. # be interpolated against the values of Field.__dict__ before being output.
  127. # If a column type is set to None, it won't be included in the output.
  128. _data_types = {
  129. 'AutoField': 'integer AUTO_INCREMENT',
  130. 'BigAutoField': 'bigint AUTO_INCREMENT',
  131. 'BinaryField': 'longblob',
  132. 'BooleanField': 'bool',
  133. 'CharField': 'varchar(%(max_length)s)',
  134. 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
  135. 'DateField': 'date',
  136. 'DateTimeField': 'datetime',
  137. 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
  138. 'DurationField': 'bigint',
  139. 'FileField': 'varchar(%(max_length)s)',
  140. 'FilePathField': 'varchar(%(max_length)s)',
  141. 'FloatField': 'double precision',
  142. 'IntegerField': 'integer',
  143. 'BigIntegerField': 'bigint',
  144. 'IPAddressField': 'char(15)',
  145. 'GenericIPAddressField': 'char(39)',
  146. 'NullBooleanField': 'bool',
  147. 'OneToOneField': 'integer',
  148. 'PositiveIntegerField': 'integer UNSIGNED',
  149. 'PositiveSmallIntegerField': 'smallint UNSIGNED',
  150. 'SlugField': 'varchar(%(max_length)s)',
  151. 'SmallIntegerField': 'smallint',
  152. 'TextField': 'longtext',
  153. 'TimeField': 'time',
  154. 'UUIDField': 'char(32)',
  155. }
  156. @cached_property
  157. def data_types(self):
  158. if self.features.supports_microsecond_precision:
  159. return dict(self._data_types, DateTimeField='datetime(6)', TimeField='time(6)')
  160. else:
  161. return self._data_types
  162. operators = {
  163. 'exact': '= %s',
  164. 'iexact': 'LIKE %s',
  165. 'contains': 'LIKE BINARY %s',
  166. 'icontains': 'LIKE %s',
  167. 'regex': 'REGEXP BINARY %s',
  168. 'iregex': 'REGEXP %s',
  169. 'gt': '> %s',
  170. 'gte': '>= %s',
  171. 'lt': '< %s',
  172. 'lte': '<= %s',
  173. 'startswith': 'LIKE BINARY %s',
  174. 'endswith': 'LIKE BINARY %s',
  175. 'istartswith': 'LIKE %s',
  176. 'iendswith': 'LIKE %s',
  177. }
  178. # The patterns below are used to generate SQL pattern lookup clauses when
  179. # the right-hand side of the lookup isn't a raw string (it might be an expression
  180. # or the result of a bilateral transformation).
  181. # In those cases, special characters for LIKE operators (e.g. \, *, _) should be
  182. # escaped on database side.
  183. #
  184. # Note: we use str.format() here for readability as '%' is used as a wildcard for
  185. # the LIKE operator.
  186. pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\\', '\\\\'), '%%', '\%%'), '_', '\_')"
  187. pattern_ops = {
  188. 'contains': "LIKE BINARY CONCAT('%%', {}, '%%')",
  189. 'icontains': "LIKE CONCAT('%%', {}, '%%')",
  190. 'startswith': "LIKE BINARY CONCAT({}, '%%')",
  191. 'istartswith': "LIKE CONCAT({}, '%%')",
  192. 'endswith': "LIKE BINARY CONCAT('%%', {})",
  193. 'iendswith': "LIKE CONCAT('%%', {})",
  194. }
  195. Database = Database
  196. SchemaEditorClass = DatabaseSchemaEditor
  197. def __init__(self, *args, **kwargs):
  198. super(DatabaseWrapper, self).__init__(*args, **kwargs)
  199. self.features = DatabaseFeatures(self)
  200. self.ops = DatabaseOperations(self)
  201. self.client = DatabaseClient(self)
  202. self.creation = DatabaseCreation(self)
  203. self.introspection = DatabaseIntrospection(self)
  204. self.validation = DatabaseValidation(self)
  205. def get_connection_params(self):
  206. kwargs = {
  207. 'conv': django_conversions,
  208. 'charset': 'utf8',
  209. }
  210. if six.PY2:
  211. kwargs['use_unicode'] = True
  212. settings_dict = self.settings_dict
  213. if settings_dict['USER']:
  214. kwargs['user'] = settings_dict['USER']
  215. if settings_dict['NAME']:
  216. kwargs['db'] = settings_dict['NAME']
  217. if settings_dict['PASSWORD']:
  218. kwargs['passwd'] = force_str(settings_dict['PASSWORD'])
  219. if settings_dict['HOST'].startswith('/'):
  220. kwargs['unix_socket'] = settings_dict['HOST']
  221. elif settings_dict['HOST']:
  222. kwargs['host'] = settings_dict['HOST']
  223. if settings_dict['PORT']:
  224. kwargs['port'] = int(settings_dict['PORT'])
  225. # We need the number of potentially affected rows after an
  226. # "UPDATE", not the number of changed rows.
  227. kwargs['client_flag'] = CLIENT.FOUND_ROWS
  228. kwargs.update(settings_dict['OPTIONS'])
  229. return kwargs
  230. def get_new_connection(self, conn_params):
  231. conn = Database.connect(**conn_params)
  232. conn.encoders[SafeText] = conn.encoders[six.text_type]
  233. conn.encoders[SafeBytes] = conn.encoders[bytes]
  234. return conn
  235. def init_connection_state(self):
  236. if self.features.is_sql_auto_is_null_enabled:
  237. with self.cursor() as cursor:
  238. # SQL_AUTO_IS_NULL controls whether an AUTO_INCREMENT column on
  239. # a recently inserted row will return when the field is tested
  240. # for NULL. Disabling this brings this aspect of MySQL in line
  241. # with SQL standards.
  242. cursor.execute('SET SQL_AUTO_IS_NULL = 0')
  243. def create_cursor(self):
  244. cursor = self.connection.cursor()
  245. return CursorWrapper(cursor)
  246. def _rollback(self):
  247. try:
  248. BaseDatabaseWrapper._rollback(self)
  249. except Database.NotSupportedError:
  250. pass
  251. def _set_autocommit(self, autocommit):
  252. with self.wrap_database_errors:
  253. self.connection.autocommit(autocommit)
  254. def disable_constraint_checking(self):
  255. """
  256. Disables foreign key checks, primarily for use in adding rows with forward references. Always returns True,
  257. to indicate constraint checks need to be re-enabled.
  258. """
  259. self.cursor().execute('SET foreign_key_checks=0')
  260. return True
  261. def enable_constraint_checking(self):
  262. """
  263. Re-enable foreign key checks after they have been disabled.
  264. """
  265. # Override needs_rollback in case constraint_checks_disabled is
  266. # nested inside transaction.atomic.
  267. self.needs_rollback, needs_rollback = False, self.needs_rollback
  268. try:
  269. self.cursor().execute('SET foreign_key_checks=1')
  270. finally:
  271. self.needs_rollback = needs_rollback
  272. def check_constraints(self, table_names=None):
  273. """
  274. Checks each table name in `table_names` for rows with invalid foreign
  275. key references. This method is intended to be used in conjunction with
  276. `disable_constraint_checking()` and `enable_constraint_checking()`, to
  277. determine if rows with invalid references were entered while constraint
  278. checks were off.
  279. Raises an IntegrityError on the first invalid foreign key reference
  280. encountered (if any) and provides detailed information about the
  281. invalid reference in the error message.
  282. Backends can override this method if they can more directly apply
  283. constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
  284. """
  285. cursor = self.cursor()
  286. if table_names is None:
  287. table_names = self.introspection.table_names(cursor)
  288. for table_name in table_names:
  289. primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
  290. if not primary_key_column_name:
  291. continue
  292. key_columns = self.introspection.get_key_columns(cursor, table_name)
  293. for column_name, referenced_table_name, referenced_column_name in key_columns:
  294. cursor.execute("""
  295. SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
  296. LEFT JOIN `%s` as REFERRED
  297. ON (REFERRING.`%s` = REFERRED.`%s`)
  298. WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
  299. % (primary_key_column_name, column_name, table_name, referenced_table_name,
  300. column_name, referenced_column_name, column_name, referenced_column_name))
  301. for bad_row in cursor.fetchall():
  302. raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
  303. "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
  304. % (table_name, bad_row[0],
  305. table_name, column_name, bad_row[1],
  306. referenced_table_name, referenced_column_name))
  307. def is_usable(self):
  308. try:
  309. self.connection.ping()
  310. except Database.Error:
  311. return False
  312. else:
  313. return True
  314. @cached_property
  315. def mysql_version(self):
  316. with self.temporary_connection():
  317. server_info = self.connection.get_server_info()
  318. match = server_version_re.match(server_info)
  319. if not match:
  320. raise Exception('Unable to determine MySQL version from version string %r' % server_info)
  321. return tuple(int(x) for x in match.groups())