Ticket #29572: base.py

File base.py, 13.8 KB (added by BobDu, 6 years ago)

This is the repair file ./django/django/db/backends/mysql/base.py

Line 
1"""
2MySQL database backend for Django.
3
4Requires mysqlclient: https://pypi.org/project/mysqlclient/
5"""
6import re
7
8from django.core.exceptions import ImproperlyConfigured
9from django.db import utils
10from django.db.backends import utils as backend_utils
11from django.db.backends.base.base import BaseDatabaseWrapper
12from django.utils.functional import cached_property
13
14try:
15 import pymysql as Database
16 pymysql.install_as_MySQLdb()
17except ImportError as err:
18 raise ImproperlyConfigured(
19 'Error loading MySQLdb module.\n'
20 'Did you install mysqlclient?'
21 ) from err
22
23from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip
24from MySQLdb.converters import conversions # isort:skip
25
26# Some of these import MySQLdb, so import them after checking if it's installed.
27from .client import DatabaseClient # isort:skip
28from .creation import DatabaseCreation # isort:skip
29from .features import DatabaseFeatures # isort:skip
30from .introspection import DatabaseIntrospection # isort:skip
31from .operations import DatabaseOperations # isort:skip
32from .schema import DatabaseSchemaEditor # isort:skip
33from .validation import DatabaseValidation # isort:skip
34
35version = Database.version_info
36if version < (1, 3, 7):
37 raise ImproperlyConfigured('mysqlclient 1.3.7 or newer is required; you have %s.' % Database.__version__)
38
39
40# MySQLdb returns TIME columns as timedelta -- they are more like timedelta in
41# terms of actual behavior as they are signed and include days -- and Django
42# expects time.
43django_conversions = {
44 **conversions,
45 **{FIELD_TYPE.TIME: backend_utils.typecast_time},
46}
47
48# This should match the numerical portion of the version numbers (we can treat
49# versions like 5.0.24 and 5.0.24a as the same).
50server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
51
52
53class CursorWrapper:
54 """
55 A thin wrapper around MySQLdb's normal cursor class that catches particular
56 exception instances and reraises them with the correct types.
57
58 Implemented as a wrapper, rather than a subclass, so that it isn't stuck
59 to the particular underlying representation returned by Connection.cursor().
60 """
61 codes_for_integrityerror = (
62 1048, # Column cannot be null
63 1690, # BIGINT UNSIGNED value is out of range
64 )
65
66 def __init__(self, cursor):
67 self.cursor = cursor
68
69 def execute(self, query, args=None):
70 try:
71 # args is None means no string interpolation
72 return self.cursor.execute(query, args)
73 except Database.OperationalError as e:
74 # Map some error codes to IntegrityError, since they seem to be
75 # misclassified and Django would prefer the more logical place.
76 if e.args[0] in self.codes_for_integrityerror:
77 raise utils.IntegrityError(*tuple(e.args))
78 raise
79
80 def executemany(self, query, args):
81 try:
82 return self.cursor.executemany(query, args)
83 except Database.OperationalError as e:
84 # Map some error codes to IntegrityError, since they seem to be
85 # misclassified and Django would prefer the more logical place.
86 if e.args[0] in self.codes_for_integrityerror:
87 raise utils.IntegrityError(*tuple(e.args))
88 raise
89
90 def __getattr__(self, attr):
91 return getattr(self.cursor, attr)
92
93 def __iter__(self):
94 return iter(self.cursor)
95
96
97class DatabaseWrapper(BaseDatabaseWrapper):
98 vendor = 'mysql'
99 display_name = 'MySQL'
100 # This dictionary maps Field objects to their associated MySQL column
101 # types, as strings. Column-type strings can contain format strings; they'll
102 # be interpolated against the values of Field.__dict__ before being output.
103 # If a column type is set to None, it won't be included in the output.
104 data_types = {
105 'AutoField': 'integer AUTO_INCREMENT',
106 'BigAutoField': 'bigint AUTO_INCREMENT',
107 'BinaryField': 'longblob',
108 'BooleanField': 'bool',
109 'CharField': 'varchar(%(max_length)s)',
110 'DateField': 'date',
111 'DateTimeField': 'datetime(6)',
112 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
113 'DurationField': 'bigint',
114 'FileField': 'varchar(%(max_length)s)',
115 'FilePathField': 'varchar(%(max_length)s)',
116 'FloatField': 'double precision',
117 'IntegerField': 'integer',
118 'BigIntegerField': 'bigint',
119 'IPAddressField': 'char(15)',
120 'GenericIPAddressField': 'char(39)',
121 'NullBooleanField': 'bool',
122 'OneToOneField': 'integer',
123 'PositiveIntegerField': 'integer UNSIGNED',
124 'PositiveSmallIntegerField': 'smallint UNSIGNED',
125 'SlugField': 'varchar(%(max_length)s)',
126 'SmallIntegerField': 'smallint',
127 'TextField': 'longtext',
128 'TimeField': 'time(6)',
129 'UUIDField': 'char(32)',
130 }
131
132 # For these columns, MySQL doesn't:
133 # - accept default values and implicitly treats these columns as nullable
134 # - support a database index
135 _limited_data_types = (
136 'tinyblob', 'blob', 'mediumblob', 'longblob', 'tinytext', 'text',
137 'mediumtext', 'longtext', 'json',
138 )
139
140 operators = {
141 'exact': '= %s',
142 'iexact': 'LIKE %s',
143 'contains': 'LIKE BINARY %s',
144 'icontains': 'LIKE %s',
145 'gt': '> %s',
146 'gte': '>= %s',
147 'lt': '< %s',
148 'lte': '<= %s',
149 'startswith': 'LIKE BINARY %s',
150 'endswith': 'LIKE BINARY %s',
151 'istartswith': 'LIKE %s',
152 'iendswith': 'LIKE %s',
153 }
154
155 # The patterns below are used to generate SQL pattern lookup clauses when
156 # the right-hand side of the lookup isn't a raw string (it might be an expression
157 # or the result of a bilateral transformation).
158 # In those cases, special characters for LIKE operators (e.g. \, *, _) should be
159 # escaped on database side.
160 #
161 # Note: we use str.format() here for readability as '%' is used as a wildcard for
162 # the LIKE operator.
163 pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\\', '\\\\'), '%%', '\%%'), '_', '\_')"
164 pattern_ops = {
165 'contains': "LIKE BINARY CONCAT('%%', {}, '%%')",
166 'icontains': "LIKE CONCAT('%%', {}, '%%')",
167 'startswith': "LIKE BINARY CONCAT({}, '%%')",
168 'istartswith': "LIKE CONCAT({}, '%%')",
169 'endswith': "LIKE BINARY CONCAT('%%', {})",
170 'iendswith': "LIKE CONCAT('%%', {})",
171 }
172
173 isolation_levels = {
174 'read uncommitted',
175 'read committed',
176 'repeatable read',
177 'serializable',
178 }
179
180 Database = Database
181 SchemaEditorClass = DatabaseSchemaEditor
182 # Classes instantiated in __init__().
183 client_class = DatabaseClient
184 creation_class = DatabaseCreation
185 features_class = DatabaseFeatures
186 introspection_class = DatabaseIntrospection
187 ops_class = DatabaseOperations
188 validation_class = DatabaseValidation
189
190 def get_connection_params(self):
191 kwargs = {
192 'conv': django_conversions,
193 'charset': 'utf8',
194 }
195 settings_dict = self.settings_dict
196 if settings_dict['USER']:
197 kwargs['user'] = settings_dict['USER']
198 if settings_dict['NAME']:
199 kwargs['db'] = settings_dict['NAME']
200 if settings_dict['PASSWORD']:
201 kwargs['passwd'] = settings_dict['PASSWORD']
202 if settings_dict['HOST'].startswith('/'):
203 kwargs['unix_socket'] = settings_dict['HOST']
204 elif settings_dict['HOST']:
205 kwargs['host'] = settings_dict['HOST']
206 if settings_dict['PORT']:
207 kwargs['port'] = int(settings_dict['PORT'])
208 # We need the number of potentially affected rows after an
209 # "UPDATE", not the number of changed rows.
210 kwargs['client_flag'] = CLIENT.FOUND_ROWS
211 # Validate the transaction isolation level, if specified.
212 options = settings_dict['OPTIONS'].copy()
213 isolation_level = options.pop('isolation_level', 'read committed')
214 if isolation_level:
215 isolation_level = isolation_level.lower()
216 if isolation_level not in self.isolation_levels:
217 raise ImproperlyConfigured(
218 "Invalid transaction isolation level '%s' specified.\n"
219 "Use one of %s, or None." % (
220 isolation_level,
221 ', '.join("'%s'" % s for s in sorted(self.isolation_levels))
222 ))
223 self.isolation_level = isolation_level
224 kwargs.update(options)
225 return kwargs
226
227 def get_new_connection(self, conn_params):
228 return Database.connect(**conn_params)
229
230 def init_connection_state(self):
231 assignments = []
232 if self.features.is_sql_auto_is_null_enabled:
233 # SQL_AUTO_IS_NULL controls whether an AUTO_INCREMENT column on
234 # a recently inserted row will return when the field is tested
235 # for NULL. Disabling this brings this aspect of MySQL in line
236 # with SQL standards.
237 assignments.append('SET SQL_AUTO_IS_NULL = 0')
238
239 if self.isolation_level:
240 assignments.append('SET SESSION TRANSACTION ISOLATION LEVEL %s' % self.isolation_level.upper())
241
242 if assignments:
243 with self.cursor() as cursor:
244 cursor.execute('; '.join(assignments))
245
246 def create_cursor(self, name=None):
247 cursor = self.connection.cursor()
248 return CursorWrapper(cursor)
249
250 def _rollback(self):
251 try:
252 BaseDatabaseWrapper._rollback(self)
253 except Database.NotSupportedError:
254 pass
255
256 def _set_autocommit(self, autocommit):
257 with self.wrap_database_errors:
258 self.connection.autocommit(autocommit)
259
260 def disable_constraint_checking(self):
261 """
262 Disable foreign key checks, primarily for use in adding rows with
263 forward references. Always return True to indicate constraint checks
264 need to be re-enabled.
265 """
266 self.cursor().execute('SET foreign_key_checks=0')
267 return True
268
269 def enable_constraint_checking(self):
270 """
271 Re-enable foreign key checks after they have been disabled.
272 """
273 # Override needs_rollback in case constraint_checks_disabled is
274 # nested inside transaction.atomic.
275 self.needs_rollback, needs_rollback = False, self.needs_rollback
276 try:
277 self.cursor().execute('SET foreign_key_checks=1')
278 finally:
279 self.needs_rollback = needs_rollback
280
281 def check_constraints(self, table_names=None):
282 """
283 Check each table name in `table_names` for rows with invalid foreign
284 key references. This method is intended to be used in conjunction with
285 `disable_constraint_checking()` and `enable_constraint_checking()`, to
286 determine if rows with invalid references were entered while constraint
287 checks were off.
288 """
289 with self.cursor() as cursor:
290 if table_names is None:
291 table_names = self.introspection.table_names(cursor)
292 for table_name in table_names:
293 primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
294 if not primary_key_column_name:
295 continue
296 key_columns = self.introspection.get_key_columns(cursor, table_name)
297 for column_name, referenced_table_name, referenced_column_name in key_columns:
298 cursor.execute(
299 """
300 SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
301 LEFT JOIN `%s` as REFERRED
302 ON (REFERRING.`%s` = REFERRED.`%s`)
303 WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
304 """ % (
305 primary_key_column_name, column_name, table_name,
306 referenced_table_name, column_name, referenced_column_name,
307 column_name, referenced_column_name,
308 )
309 )
310 for bad_row in cursor.fetchall():
311 raise utils.IntegrityError(
312 "The row in table '%s' with primary key '%s' has an invalid "
313 "foreign key: %s.%s contains a value '%s' that does not "
314 "have a corresponding value in %s.%s."
315 % (
316 table_name, bad_row[0], table_name, column_name,
317 bad_row[1], referenced_table_name, referenced_column_name,
318 )
319 )
320
321 def is_usable(self):
322 try:
323 self.connection.ping()
324 except Database.Error:
325 return False
326 else:
327 return True
328
329 @cached_property
330 def mysql_server_info(self):
331 with self.temporary_connection() as cursor:
332 cursor.execute('SELECT VERSION()')
333 return cursor.fetchone()[0]
334
335 @cached_property
336 def mysql_version(self):
337 match = server_version_re.match(self.mysql_server_info)
338 if not match:
339 raise Exception('Unable to determine MySQL version from version string %r' % self.mysql_server_info)
340 return tuple(int(x) for x in match.groups())
341
342 @cached_property
343 def mysql_is_mariadb(self):
344 # MariaDB isn't officially supported.
345 return 'mariadb' in self.mysql_server_info.lower()
Back to Top