PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

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