Ticket #29678: base.py

File base.py, 13.5 KB (added by SuilAmhain, 6 years ago)

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