django-tidb 1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 1.1
2
+ Name: django_tidb
3
+ Version: 1.0
4
+ Summary: TiDB backend for Django
5
+ Home-page: http://github.com/blacktear23/django_tidb
6
+ Author: Rain Li
7
+ Author-email: blacktear23@gmail.com
8
+ License: Apache2
9
+ Download-URL: http://github.com/blackear23/django_tidb/archive/1.0.tar.gz
10
+ Description: TiDB backend for Django
11
+ Keywords: django,tidb
12
+ Platform: UNKNOWN
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 2
17
+ Classifier: Topic :: Software Development :: Libraries
File without changes
File without changes
@@ -0,0 +1,376 @@
1
+ """
2
+ MySQL database backend for Django.
3
+
4
+ Requires mysqlclient: https://pypi.python.org/pypi/mysqlclient/
5
+ MySQLdb is supported for Python 2 only: http://sourceforge.net/projects/mysql-python
6
+ """
7
+ from __future__ import unicode_literals
8
+
9
+ import datetime
10
+ import re
11
+ import sys
12
+ import warnings
13
+
14
+ from django.conf import settings
15
+ from django.db import utils
16
+ from django.db.backends import utils as backend_utils
17
+ from django.db.backends.base.base import BaseDatabaseWrapper
18
+ from django.utils import six, timezone
19
+ from django.utils.encoding import force_str
20
+ from django.utils.functional import cached_property
21
+ from django.utils.safestring import SafeBytes, SafeText
22
+
23
+ try:
24
+ import MySQLdb as Database
25
+ except ImportError as e:
26
+ from django.core.exceptions import ImproperlyConfigured
27
+ raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
28
+
29
+ from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip
30
+ from MySQLdb.converters import Thing2Literal, conversions # isort:skip
31
+
32
+ # Some of these import MySQLdb, so import them after checking if it's installed.
33
+ from .client import DatabaseClient # isort:skip
34
+ from .creation import DatabaseCreation # isort:skip
35
+ from .features import DatabaseFeatures # isort:skip
36
+ from .introspection import DatabaseIntrospection # isort:skip
37
+ from .operations import DatabaseOperations # isort:skip
38
+ from .schema import DatabaseSchemaEditor # isort:skip
39
+ from .validation import DatabaseValidation # isort:skip
40
+
41
+ # We want version (1, 2, 1, 'final', 2) or later. We can't just use
42
+ # lexicographic ordering in this check because then (1, 2, 1, 'gamma')
43
+ # inadvertently passes the version test.
44
+ version = Database.version_info
45
+ if (version < (1, 2, 1) or (version[:3] == (1, 2, 1) and
46
+ (len(version) < 5 or version[3] != 'final' or version[4] < 2))):
47
+ from django.core.exceptions import ImproperlyConfigured
48
+ raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__)
49
+
50
+
51
+ DatabaseError = Database.DatabaseError
52
+ IntegrityError = Database.IntegrityError
53
+
54
+ # It's impossible to import datetime_or_None directly from MySQLdb.times
55
+ parse_datetime = conversions[FIELD_TYPE.DATETIME]
56
+
57
+
58
+ def parse_datetime_with_timezone_support(value):
59
+ dt = parse_datetime(value)
60
+ # Confirm that dt is naive before overwriting its tzinfo.
61
+ if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
62
+ dt = dt.replace(tzinfo=timezone.utc)
63
+ return dt
64
+
65
+
66
+ def adapt_datetime_with_timezone_support(value, conv):
67
+ # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
68
+ if settings.USE_TZ:
69
+ if timezone.is_naive(value):
70
+ warnings.warn("MySQL received a naive datetime (%s)"
71
+ " while time zone support is active." % value,
72
+ RuntimeWarning)
73
+ default_timezone = timezone.get_default_timezone()
74
+ value = timezone.make_aware(value, default_timezone)
75
+ value = value.astimezone(timezone.utc).replace(tzinfo=None)
76
+ return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)
77
+
78
+ # MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
79
+ # timedelta in terms of actual behavior as they are signed and include days --
80
+ # and Django expects time, so we still need to override that. We also need to
81
+ # add special handling for SafeText and SafeBytes as MySQLdb's type
82
+ # checking is too tight to catch those (see Django ticket #6052).
83
+ # Finally, MySQLdb always returns naive datetime objects. However, when
84
+ # timezone support is active, Django expects timezone-aware datetime objects.
85
+ django_conversions = conversions.copy()
86
+ django_conversions.update({
87
+ FIELD_TYPE.TIME: backend_utils.typecast_time,
88
+ FIELD_TYPE.DECIMAL: backend_utils.typecast_decimal,
89
+ FIELD_TYPE.NEWDECIMAL: backend_utils.typecast_decimal,
90
+ FIELD_TYPE.DATETIME: parse_datetime_with_timezone_support,
91
+ datetime.datetime: adapt_datetime_with_timezone_support,
92
+ })
93
+
94
+ # This should match the numerical portion of the version numbers (we can treat
95
+ # versions like 5.0.24 and 5.0.24a as the same). Based on the list of version
96
+ # at http://dev.mysql.com/doc/refman/4.1/en/news.html and
97
+ # http://dev.mysql.com/doc/refman/5.0/en/news.html .
98
+ server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')
99
+
100
+
101
+ # MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
102
+ # MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
103
+ # point is to raise Warnings as exceptions, this can be done with the Python
104
+ # warning module, and this is setup when the connection is created, and the
105
+ # standard backend_utils.CursorDebugWrapper can be used. Also, using sql_mode
106
+ # TRADITIONAL will automatically cause most warnings to be treated as errors.
107
+
108
+ class CursorWrapper(object):
109
+ """
110
+ A thin wrapper around MySQLdb's normal cursor class so that we can catch
111
+ particular exception instances and reraise them with the right types.
112
+
113
+ Implemented as a wrapper, rather than a subclass, so that we aren't stuck
114
+ to the particular underlying representation returned by Connection.cursor().
115
+ """
116
+ codes_for_integrityerror = (1048,)
117
+
118
+ def __init__(self, cursor):
119
+ self.cursor = cursor
120
+
121
+ def execute(self, query, args=None):
122
+ try:
123
+ # args is None means no string interpolation
124
+ return self.cursor.execute(query, args)
125
+ except Database.OperationalError as e:
126
+ # Map some error codes to IntegrityError, since they seem to be
127
+ # misclassified and Django would prefer the more logical place.
128
+ if e.args[0] in self.codes_for_integrityerror:
129
+ six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
130
+ raise
131
+
132
+ def executemany(self, query, args):
133
+ try:
134
+ return self.cursor.executemany(query, args)
135
+ except Database.OperationalError as e:
136
+ # Map some error codes to IntegrityError, since they seem to be
137
+ # misclassified and Django would prefer the more logical place.
138
+ if e.args[0] in self.codes_for_integrityerror:
139
+ six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
140
+ raise
141
+
142
+ def __getattr__(self, attr):
143
+ if attr in self.__dict__:
144
+ return self.__dict__[attr]
145
+ else:
146
+ return getattr(self.cursor, attr)
147
+
148
+ def __iter__(self):
149
+ return iter(self.cursor)
150
+
151
+ def __enter__(self):
152
+ return self
153
+
154
+ def __exit__(self, type, value, traceback):
155
+ # Ticket #17671 - Close instead of passing thru to avoid backend
156
+ # specific behavior.
157
+ self.close()
158
+
159
+
160
+ class DatabaseWrapper(BaseDatabaseWrapper):
161
+ vendor = 'mysql'
162
+ # This dictionary maps Field objects to their associated MySQL column
163
+ # types, as strings. Column-type strings can contain format strings; they'll
164
+ # be interpolated against the values of Field.__dict__ before being output.
165
+ # If a column type is set to None, it won't be included in the output.
166
+ _data_types = {
167
+ 'AutoField': 'integer AUTO_INCREMENT',
168
+ 'BinaryField': 'longblob',
169
+ 'BooleanField': 'bool',
170
+ 'CharField': 'varchar(%(max_length)s)',
171
+ 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
172
+ 'DateField': 'date',
173
+ 'DateTimeField': 'datetime',
174
+ 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
175
+ 'DurationField': 'bigint',
176
+ 'FileField': 'varchar(%(max_length)s)',
177
+ 'FilePathField': 'varchar(%(max_length)s)',
178
+ 'FloatField': 'double precision',
179
+ 'IntegerField': 'integer',
180
+ 'BigIntegerField': 'bigint',
181
+ 'IPAddressField': 'char(15)',
182
+ 'GenericIPAddressField': 'char(39)',
183
+ 'NullBooleanField': 'bool',
184
+ 'OneToOneField': 'integer',
185
+ 'PositiveIntegerField': 'integer UNSIGNED',
186
+ 'PositiveSmallIntegerField': 'smallint UNSIGNED',
187
+ 'SlugField': 'varchar(%(max_length)s)',
188
+ 'SmallIntegerField': 'smallint',
189
+ 'TextField': 'longtext',
190
+ 'TimeField': 'time',
191
+ 'UUIDField': 'char(32)',
192
+ }
193
+
194
+ @cached_property
195
+ def data_types(self):
196
+ if self.features.supports_microsecond_precision:
197
+ return dict(self._data_types, DateTimeField='datetime(6)', TimeField='time(6)')
198
+ else:
199
+ return self._data_types
200
+
201
+ operators = {
202
+ 'exact': '= %s',
203
+ 'iexact': 'LIKE %s',
204
+ 'contains': 'LIKE BINARY %s',
205
+ 'icontains': 'LIKE %s',
206
+ 'regex': 'REGEXP BINARY %s',
207
+ 'iregex': 'REGEXP %s',
208
+ 'gt': '> %s',
209
+ 'gte': '>= %s',
210
+ 'lt': '< %s',
211
+ 'lte': '<= %s',
212
+ 'startswith': 'LIKE BINARY %s',
213
+ 'endswith': 'LIKE BINARY %s',
214
+ 'istartswith': 'LIKE %s',
215
+ 'iendswith': 'LIKE %s',
216
+ }
217
+
218
+ # The patterns below are used to generate SQL pattern lookup clauses when
219
+ # the right-hand side of the lookup isn't a raw string (it might be an expression
220
+ # or the result of a bilateral transformation).
221
+ # In those cases, special characters for LIKE operators (e.g. \, *, _) should be
222
+ # escaped on database side.
223
+ #
224
+ # Note: we use str.format() here for readability as '%' is used as a wildcard for
225
+ # the LIKE operator.
226
+ pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\\', '\\\\'), '%%', '\%%'), '_', '\_')"
227
+ pattern_ops = {
228
+ 'contains': "LIKE BINARY CONCAT('%%', {}, '%%')",
229
+ 'icontains': "LIKE CONCAT('%%', {}, '%%')",
230
+ 'startswith': "LIKE BINARY CONCAT({}, '%%')",
231
+ 'istartswith': "LIKE CONCAT({}, '%%')",
232
+ 'endswith': "LIKE BINARY CONCAT('%%', {})",
233
+ 'iendswith': "LIKE CONCAT('%%', {})",
234
+ }
235
+
236
+ Database = Database
237
+ SchemaEditorClass = DatabaseSchemaEditor
238
+
239
+ def __init__(self, *args, **kwargs):
240
+ super(DatabaseWrapper, self).__init__(*args, **kwargs)
241
+
242
+ self.features = DatabaseFeatures(self)
243
+ self.ops = DatabaseOperations(self)
244
+ self.client = DatabaseClient(self)
245
+ self.creation = DatabaseCreation(self)
246
+ self.introspection = DatabaseIntrospection(self)
247
+ self.validation = DatabaseValidation(self)
248
+
249
+ def get_connection_params(self):
250
+ kwargs = {
251
+ 'conv': django_conversions,
252
+ 'charset': 'utf8',
253
+ }
254
+ if six.PY2:
255
+ kwargs['use_unicode'] = True
256
+ settings_dict = self.settings_dict
257
+ if settings_dict['USER']:
258
+ kwargs['user'] = settings_dict['USER']
259
+ if settings_dict['NAME']:
260
+ kwargs['db'] = settings_dict['NAME']
261
+ if settings_dict['PASSWORD']:
262
+ kwargs['passwd'] = force_str(settings_dict['PASSWORD'])
263
+ if settings_dict['HOST'].startswith('/'):
264
+ kwargs['unix_socket'] = settings_dict['HOST']
265
+ elif settings_dict['HOST']:
266
+ kwargs['host'] = settings_dict['HOST']
267
+ if settings_dict['PORT']:
268
+ kwargs['port'] = int(settings_dict['PORT'])
269
+ # We need the number of potentially affected rows after an
270
+ # "UPDATE", not the number of changed rows.
271
+ kwargs['client_flag'] = CLIENT.FOUND_ROWS
272
+ kwargs.update(settings_dict['OPTIONS'])
273
+ return kwargs
274
+
275
+ def get_new_connection(self, conn_params):
276
+ conn = Database.connect(**conn_params)
277
+ conn.encoders[SafeText] = conn.encoders[six.text_type]
278
+ conn.encoders[SafeBytes] = conn.encoders[bytes]
279
+ return conn
280
+
281
+ def init_connection_state(self):
282
+ with self.cursor() as cursor:
283
+ # SQL_AUTO_IS_NULL in MySQL controls whether an AUTO_INCREMENT column
284
+ # on a recently-inserted row will return when the field is tested for
285
+ # NULL. Disabling this value brings this aspect of MySQL in line with
286
+ # SQL standards.
287
+ cursor.execute('SET SQL_AUTO_IS_NULL = 0')
288
+
289
+ def create_cursor(self):
290
+ cursor = self.connection.cursor()
291
+ return CursorWrapper(cursor)
292
+
293
+ def _rollback(self):
294
+ try:
295
+ BaseDatabaseWrapper._rollback(self)
296
+ except Database.NotSupportedError:
297
+ pass
298
+
299
+ def _set_autocommit(self, autocommit):
300
+ with self.wrap_database_errors:
301
+ self.connection.autocommit(autocommit)
302
+
303
+ def disable_constraint_checking(self):
304
+ """
305
+ Disables foreign key checks, primarily for use in adding rows with forward references. Always returns True,
306
+ to indicate constraint checks need to be re-enabled.
307
+ """
308
+ self.cursor().execute('SET foreign_key_checks=0')
309
+ return True
310
+
311
+ def enable_constraint_checking(self):
312
+ """
313
+ Re-enable foreign key checks after they have been disabled.
314
+ """
315
+ # Override needs_rollback in case constraint_checks_disabled is
316
+ # nested inside transaction.atomic.
317
+ self.needs_rollback, needs_rollback = False, self.needs_rollback
318
+ try:
319
+ self.cursor().execute('SET foreign_key_checks=1')
320
+ finally:
321
+ self.needs_rollback = needs_rollback
322
+
323
+ def check_constraints(self, table_names=None):
324
+ """
325
+ Checks each table name in `table_names` for rows with invalid foreign
326
+ key references. This method is intended to be used in conjunction with
327
+ `disable_constraint_checking()` and `enable_constraint_checking()`, to
328
+ determine if rows with invalid references were entered while constraint
329
+ checks were off.
330
+
331
+ Raises an IntegrityError on the first invalid foreign key reference
332
+ encountered (if any) and provides detailed information about the
333
+ invalid reference in the error message.
334
+
335
+ Backends can override this method if they can more directly apply
336
+ constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
337
+ """
338
+ cursor = self.cursor()
339
+ if table_names is None:
340
+ table_names = self.introspection.table_names(cursor)
341
+ for table_name in table_names:
342
+ primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
343
+ if not primary_key_column_name:
344
+ continue
345
+ key_columns = self.introspection.get_key_columns(cursor, table_name)
346
+ for column_name, referenced_table_name, referenced_column_name in key_columns:
347
+ cursor.execute("""
348
+ SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
349
+ LEFT JOIN `%s` as REFERRED
350
+ ON (REFERRING.`%s` = REFERRED.`%s`)
351
+ WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
352
+ % (primary_key_column_name, column_name, table_name, referenced_table_name,
353
+ column_name, referenced_column_name, column_name, referenced_column_name))
354
+ for bad_row in cursor.fetchall():
355
+ raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
356
+ "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
357
+ % (table_name, bad_row[0],
358
+ table_name, column_name, bad_row[1],
359
+ referenced_table_name, referenced_column_name))
360
+
361
+ def is_usable(self):
362
+ try:
363
+ self.connection.ping()
364
+ except Database.Error:
365
+ return False
366
+ else:
367
+ return True
368
+
369
+ @cached_property
370
+ def mysql_version(self):
371
+ with self.temporary_connection():
372
+ server_info = self.connection.get_server_info()
373
+ match = server_version_re.match(server_info)
374
+ if not match:
375
+ raise Exception('Unable to determine MySQL version from version string %r' % server_info)
376
+ return tuple(int(x) for x in match.groups())
@@ -0,0 +1,42 @@
1
+ import subprocess
2
+
3
+ from django.db.backends.base.client import BaseDatabaseClient
4
+
5
+
6
+ class DatabaseClient(BaseDatabaseClient):
7
+ executable_name = 'mysql'
8
+
9
+ @classmethod
10
+ def settings_to_cmd_args(cls, settings_dict):
11
+ args = [cls.executable_name]
12
+ db = settings_dict['OPTIONS'].get('db', settings_dict['NAME'])
13
+ user = settings_dict['OPTIONS'].get('user', settings_dict['USER'])
14
+ passwd = settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD'])
15
+ host = settings_dict['OPTIONS'].get('host', settings_dict['HOST'])
16
+ port = settings_dict['OPTIONS'].get('port', settings_dict['PORT'])
17
+ cert = settings_dict['OPTIONS'].get('ssl', {}).get('ca')
18
+ defaults_file = settings_dict['OPTIONS'].get('read_default_file')
19
+ # Seems to be no good way to set sql_mode with CLI.
20
+
21
+ if defaults_file:
22
+ args += ["--defaults-file=%s" % defaults_file]
23
+ if user:
24
+ args += ["--user=%s" % user]
25
+ if passwd:
26
+ args += ["--password=%s" % passwd]
27
+ if host:
28
+ if '/' in host:
29
+ args += ["--socket=%s" % host]
30
+ else:
31
+ args += ["--host=%s" % host]
32
+ if port:
33
+ args += ["--port=%s" % port]
34
+ if cert:
35
+ args += ["--ssl-ca=%s" % cert]
36
+ if db:
37
+ args += [db]
38
+ return args
39
+
40
+ def runshell(self):
41
+ args = DatabaseClient.settings_to_cmd_args(self.connection.settings_dict)
42
+ subprocess.call(args)
@@ -0,0 +1,25 @@
1
+ from django.db.models.sql import compiler
2
+
3
+
4
+ class SQLCompiler(compiler.SQLCompiler):
5
+ def as_subquery_condition(self, alias, columns, compiler):
6
+ qn = compiler.quote_name_unless_alias
7
+ qn2 = self.connection.ops.quote_name
8
+ sql, params = self.as_sql()
9
+ return '(%s) IN (%s)' % (', '.join('%s.%s' % (qn(alias), qn2(column)) for column in columns), sql), params
10
+
11
+
12
+ class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
13
+ pass
14
+
15
+
16
+ class SQLDeleteCompiler(compiler.SQLDeleteCompiler, SQLCompiler):
17
+ pass
18
+
19
+
20
+ class SQLUpdateCompiler(compiler.SQLUpdateCompiler, SQLCompiler):
21
+ pass
22
+
23
+
24
+ class SQLAggregateCompiler(compiler.SQLAggregateCompiler, SQLCompiler):
25
+ pass
@@ -0,0 +1,43 @@
1
+ from django.db.backends.base.creation import BaseDatabaseCreation
2
+
3
+
4
+ class DatabaseCreation(BaseDatabaseCreation):
5
+
6
+ def sql_table_creation_suffix(self):
7
+ suffix = []
8
+ test_settings = self.connection.settings_dict['TEST']
9
+ if test_settings['CHARSET']:
10
+ suffix.append('CHARACTER SET %s' % test_settings['CHARSET'])
11
+ if test_settings['COLLATION']:
12
+ suffix.append('COLLATE %s' % test_settings['COLLATION'])
13
+ return ' '.join(suffix)
14
+
15
+ def sql_for_inline_foreign_key_references(self, model, field, known_models, style):
16
+ "All inline references are pending under MySQL"
17
+ return [], True
18
+
19
+ def sql_destroy_indexes_for_fields(self, model, fields, style):
20
+ if len(fields) == 1 and fields[0].db_tablespace:
21
+ tablespace_sql = self.connection.ops.tablespace_sql(fields[0].db_tablespace)
22
+ elif model._meta.db_tablespace:
23
+ tablespace_sql = self.connection.ops.tablespace_sql(model._meta.db_tablespace)
24
+ else:
25
+ tablespace_sql = ""
26
+ if tablespace_sql:
27
+ tablespace_sql = " " + tablespace_sql
28
+
29
+ field_names = []
30
+ qn = self.connection.ops.quote_name
31
+ for f in fields:
32
+ field_names.append(style.SQL_FIELD(qn(f.column)))
33
+
34
+ index_name = "%s_%s" % (model._meta.db_table, self._digest([f.name for f in fields]))
35
+
36
+ from ..utils import truncate_name
37
+
38
+ return [
39
+ style.SQL_KEYWORD("DROP INDEX") + " " +
40
+ style.SQL_TABLE(qn(truncate_name(index_name, self.connection.ops.max_name_length()))) + " " +
41
+ style.SQL_KEYWORD("ON") + " " +
42
+ style.SQL_TABLE(qn(model._meta.db_table)) + ";",
43
+ ]
@@ -0,0 +1,71 @@
1
+ from django.db.backends.base.features import BaseDatabaseFeatures
2
+ from django.utils.functional import cached_property
3
+
4
+ from .base import Database
5
+
6
+ try:
7
+ import pytz
8
+ except ImportError:
9
+ pytz = None
10
+
11
+
12
+ class DatabaseFeatures(BaseDatabaseFeatures):
13
+ empty_fetchmany_value = ()
14
+ update_can_self_select = False
15
+ allows_group_by_pk = True
16
+ related_fields_match_type = True
17
+ allow_sliced_subqueries = False
18
+ has_bulk_insert = True
19
+ has_select_for_update = True
20
+ has_select_for_update_nowait = False
21
+ supports_forward_references = False
22
+ supports_regex_backreferencing = False
23
+ supports_date_lookup_using_string = False
24
+ supports_foreign_keys = False
25
+ can_introspect_autofield = True
26
+ can_introspect_binary_field = False
27
+ can_introspect_small_integer_field = True
28
+ supports_timezones = False
29
+ requires_explicit_null_ordering_when_grouping = True
30
+ allows_auto_pk_0 = False
31
+ uses_savepoints = True
32
+ can_release_savepoints = True
33
+ atomic_transactions = False
34
+ supports_column_check_constraints = False
35
+
36
+ @cached_property
37
+ def _mysql_storage_engine(self):
38
+ "Internal method used in Django tests. Don't rely on this from your code"
39
+ with self.connection.cursor() as cursor:
40
+ cursor.execute("SELECT ENGINE FROM INFORMATION_SCHEMA.ENGINES WHERE SUPPORT = 'DEFAULT'")
41
+ result = cursor.fetchone()
42
+ return result[0]
43
+
44
+ @cached_property
45
+ def can_introspect_foreign_keys(self):
46
+ "Confirm support for introspected foreign keys"
47
+ return self._mysql_storage_engine != 'MyISAM'
48
+
49
+ @cached_property
50
+ def supports_microsecond_precision(self):
51
+ # See https://github.com/farcepest/MySQLdb1/issues/24 for the reason
52
+ # about requiring MySQLdb 1.2.5
53
+ return self.connection.mysql_version >= (5, 6, 4) and Database.version_info >= (1, 2, 5)
54
+
55
+ @cached_property
56
+ def has_zoneinfo_database(self):
57
+ # MySQL accepts full time zones names (eg. Africa/Nairobi) but rejects
58
+ # abbreviations (eg. EAT). When pytz isn't installed and the current
59
+ # time zone is LocalTimezone (the only sensible value in this
60
+ # context), the current time zone name will be an abbreviation. As a
61
+ # consequence, MySQL cannot perform time zone conversions reliably.
62
+ if pytz is None:
63
+ return False
64
+
65
+ # Test if the time zone definitions are installed.
66
+ with self.connection.cursor() as cursor:
67
+ cursor.execute("SELECT 1 FROM mysql.time_zone LIMIT 1")
68
+ return cursor.fetchone() is not None
69
+
70
+ def introspected_boolean_field_type(self, *args, **kwargs):
71
+ return 'IntegerField'
@@ -0,0 +1,206 @@
1
+ from collections import namedtuple
2
+
3
+ from MySQLdb.constants import FIELD_TYPE
4
+
5
+ from django.db.backends.base.introspection import (
6
+ BaseDatabaseIntrospection, FieldInfo, TableInfo,
7
+ )
8
+ from django.utils.datastructures import OrderedSet
9
+ from django.utils.encoding import force_text
10
+
11
+ FieldInfo = namedtuple('FieldInfo', FieldInfo._fields + ('extra',))
12
+
13
+
14
+ class DatabaseIntrospection(BaseDatabaseIntrospection):
15
+ data_types_reverse = {
16
+ FIELD_TYPE.BLOB: 'TextField',
17
+ FIELD_TYPE.CHAR: 'CharField',
18
+ FIELD_TYPE.DECIMAL: 'DecimalField',
19
+ FIELD_TYPE.NEWDECIMAL: 'DecimalField',
20
+ FIELD_TYPE.DATE: 'DateField',
21
+ FIELD_TYPE.DATETIME: 'DateTimeField',
22
+ FIELD_TYPE.DOUBLE: 'FloatField',
23
+ FIELD_TYPE.FLOAT: 'FloatField',
24
+ FIELD_TYPE.INT24: 'IntegerField',
25
+ FIELD_TYPE.LONG: 'IntegerField',
26
+ FIELD_TYPE.LONGLONG: 'BigIntegerField',
27
+ FIELD_TYPE.SHORT: 'SmallIntegerField',
28
+ FIELD_TYPE.STRING: 'CharField',
29
+ FIELD_TYPE.TIME: 'TimeField',
30
+ FIELD_TYPE.TIMESTAMP: 'DateTimeField',
31
+ FIELD_TYPE.TINY: 'IntegerField',
32
+ FIELD_TYPE.TINY_BLOB: 'TextField',
33
+ FIELD_TYPE.MEDIUM_BLOB: 'TextField',
34
+ FIELD_TYPE.LONG_BLOB: 'TextField',
35
+ FIELD_TYPE.VAR_STRING: 'CharField',
36
+ }
37
+
38
+ def get_field_type(self, data_type, description):
39
+ field_type = super(DatabaseIntrospection, self).get_field_type(data_type, description)
40
+ if field_type == 'IntegerField' and 'auto_increment' in description.extra:
41
+ return 'AutoField'
42
+ return field_type
43
+
44
+ def get_table_list(self, cursor):
45
+ """
46
+ Returns a list of table and view names in the current database.
47
+ """
48
+ cursor.execute("SHOW FULL TABLES")
49
+ return [TableInfo(row[0], {'BASE TABLE': 't', 'VIEW': 'v'}.get(row[1]))
50
+ for row in cursor.fetchall()]
51
+
52
+ def get_table_description(self, cursor, table_name):
53
+ """
54
+ Returns a description of the table, with the DB-API cursor.description interface."
55
+ """
56
+ # information_schema database gives more accurate results for some figures:
57
+ # - varchar length returned by cursor.description is an internal length,
58
+ # not visible length (#5725)
59
+ # - precision and scale (for decimal fields) (#5014)
60
+ # - auto_increment is not available in cursor.description
61
+ InfoLine = namedtuple('InfoLine', 'col_name data_type max_len num_prec num_scale extra')
62
+ cursor.execute("""
63
+ SELECT column_name, data_type, character_maximum_length, numeric_precision, numeric_scale, extra
64
+ FROM information_schema.columns
65
+ WHERE table_name = %s AND table_schema = DATABASE()""", [table_name])
66
+ field_info = {line[0]: InfoLine(*line) for line in cursor.fetchall()}
67
+
68
+ cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name))
69
+ to_int = lambda i: int(i) if i is not None else i
70
+ fields = []
71
+ for line in cursor.description:
72
+ col_name = force_text(line[0])
73
+ fields.append(
74
+ FieldInfo(*((col_name,)
75
+ + line[1:3]
76
+ + (to_int(field_info[col_name].max_len) or line[3],
77
+ to_int(field_info[col_name].num_prec) or line[4],
78
+ to_int(field_info[col_name].num_scale) or line[5])
79
+ + (line[6],)
80
+ + (field_info[col_name].extra,)))
81
+ )
82
+ return fields
83
+
84
+ def get_relations(self, cursor, table_name):
85
+ """
86
+ Returns a dictionary of {field_name: (field_name_other_table, other_table)}
87
+ representing all relationships to the given table.
88
+ """
89
+ constraints = self.get_key_columns(cursor, table_name)
90
+ relations = {}
91
+ for my_fieldname, other_table, other_field in constraints:
92
+ relations[my_fieldname] = (other_field, other_table)
93
+ return relations
94
+
95
+ def get_key_columns(self, cursor, table_name):
96
+ """
97
+ Returns a list of (column_name, referenced_table_name, referenced_column_name) for all
98
+ key columns in given table.
99
+ """
100
+ key_columns = []
101
+ cursor.execute("""
102
+ SELECT column_name, referenced_table_name, referenced_column_name
103
+ FROM information_schema.key_column_usage
104
+ WHERE table_name = %s
105
+ AND table_schema = DATABASE()
106
+ AND referenced_table_name IS NOT NULL
107
+ AND referenced_column_name IS NOT NULL""", [table_name])
108
+ key_columns.extend(cursor.fetchall())
109
+ return key_columns
110
+
111
+ def get_indexes(self, cursor, table_name):
112
+ cursor.execute("SHOW INDEX FROM %s" % self.connection.ops.quote_name(table_name))
113
+ # Do a two-pass search for indexes: on first pass check which indexes
114
+ # are multicolumn, on second pass check which single-column indexes
115
+ # are present.
116
+ rows = list(cursor.fetchall())
117
+ multicol_indexes = set()
118
+ for row in rows:
119
+ if row[3] > 1:
120
+ multicol_indexes.add(row[2])
121
+ indexes = {}
122
+ for row in rows:
123
+ if row[2] in multicol_indexes:
124
+ continue
125
+ if row[4] not in indexes:
126
+ indexes[row[4]] = {'primary_key': False, 'unique': False}
127
+ # It's possible to have the unique and PK constraints in separate indexes.
128
+ if row[2] == 'PRIMARY':
129
+ indexes[row[4]]['primary_key'] = True
130
+ if not row[1]:
131
+ indexes[row[4]]['unique'] = True
132
+ return indexes
133
+
134
+ def get_storage_engine(self, cursor, table_name):
135
+ """
136
+ Retrieves the storage engine for a given table. Returns the default
137
+ storage engine if the table doesn't exist.
138
+ """
139
+ cursor.execute(
140
+ "SELECT engine "
141
+ "FROM information_schema.tables "
142
+ "WHERE table_name = %s", [table_name])
143
+ result = cursor.fetchone()
144
+ if not result:
145
+ return self.connection.features._mysql_storage_engine
146
+ return result[0]
147
+
148
+ def get_constraints(self, cursor, table_name):
149
+ """
150
+ Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
151
+ """
152
+ constraints = {}
153
+ # Get the actual constraint names and columns
154
+ name_query = """
155
+ SELECT kc.`constraint_name`, kc.`column_name`,
156
+ kc.`referenced_table_name`, kc.`referenced_column_name`
157
+ FROM information_schema.key_column_usage AS kc
158
+ WHERE
159
+ kc.table_schema = %s AND
160
+ kc.table_name = %s
161
+ """
162
+ cursor.execute(name_query, [self.connection.settings_dict['NAME'], table_name])
163
+ for constraint, column, ref_table, ref_column in cursor.fetchall():
164
+ if constraint not in constraints:
165
+ constraints[constraint] = {
166
+ 'columns': OrderedSet(),
167
+ 'primary_key': False,
168
+ 'unique': False,
169
+ 'index': False,
170
+ 'check': False,
171
+ 'foreign_key': (ref_table, ref_column) if ref_column else None,
172
+ }
173
+ constraints[constraint]['columns'].add(column)
174
+ # Now get the constraint types
175
+ type_query = """
176
+ SELECT c.constraint_name, c.constraint_type
177
+ FROM information_schema.table_constraints AS c
178
+ WHERE
179
+ c.table_schema = %s AND
180
+ c.table_name = %s
181
+ """
182
+ cursor.execute(type_query, [self.connection.settings_dict['NAME'], table_name])
183
+ for constraint, kind in cursor.fetchall():
184
+ if kind.lower() == "primary key":
185
+ constraints[constraint]['primary_key'] = True
186
+ constraints[constraint]['unique'] = True
187
+ elif kind.lower() == "unique":
188
+ constraints[constraint]['unique'] = True
189
+ # Now add in the indexes
190
+ cursor.execute("SHOW INDEX FROM %s" % self.connection.ops.quote_name(table_name))
191
+ for table, non_unique, index, colseq, column in [x[:5] for x in cursor.fetchall()]:
192
+ if index not in constraints:
193
+ constraints[index] = {
194
+ 'columns': OrderedSet(),
195
+ 'primary_key': False,
196
+ 'unique': False,
197
+ 'index': True,
198
+ 'check': False,
199
+ 'foreign_key': None,
200
+ }
201
+ constraints[index]['index'] = True
202
+ constraints[index]['columns'].add(column)
203
+ # Convert the sorted sets to lists
204
+ for constraint in constraints.values():
205
+ constraint['columns'] = list(constraint['columns'])
206
+ return constraints
@@ -0,0 +1,206 @@
1
+ from __future__ import unicode_literals
2
+
3
+ import uuid
4
+
5
+ from django.conf import settings
6
+ from django.db.backends.base.operations import BaseDatabaseOperations
7
+ from django.utils import six, timezone
8
+ from django.utils.encoding import force_text
9
+
10
+
11
+ class DatabaseOperations(BaseDatabaseOperations):
12
+ compiler_module = "django.db.backends.mysql.compiler"
13
+
14
+ # MySQL stores positive fields as UNSIGNED ints.
15
+ integer_field_ranges = dict(BaseDatabaseOperations.integer_field_ranges,
16
+ PositiveSmallIntegerField=(0, 65535),
17
+ PositiveIntegerField=(0, 4294967295),
18
+ )
19
+
20
+ def date_extract_sql(self, lookup_type, field_name):
21
+ # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
22
+ if lookup_type == 'week_day':
23
+ # DAYOFWEEK() returns an integer, 1-7, Sunday=1.
24
+ # Note: WEEKDAY() returns 0-6, Monday=0.
25
+ return "DAYOFWEEK(%s)" % field_name
26
+ else:
27
+ return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
28
+
29
+ def date_trunc_sql(self, lookup_type, field_name):
30
+ fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
31
+ format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
32
+ format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
33
+ try:
34
+ i = fields.index(lookup_type) + 1
35
+ except ValueError:
36
+ sql = field_name
37
+ else:
38
+ format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
39
+ sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
40
+ return sql
41
+
42
+ def datetime_extract_sql(self, lookup_type, field_name, tzname):
43
+ if settings.USE_TZ:
44
+ field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name
45
+ params = [tzname]
46
+ else:
47
+ params = []
48
+ # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
49
+ if lookup_type == 'week_day':
50
+ # DAYOFWEEK() returns an integer, 1-7, Sunday=1.
51
+ # Note: WEEKDAY() returns 0-6, Monday=0.
52
+ sql = "DAYOFWEEK(%s)" % field_name
53
+ else:
54
+ sql = "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
55
+ return sql, params
56
+
57
+ def datetime_trunc_sql(self, lookup_type, field_name, tzname):
58
+ if settings.USE_TZ:
59
+ field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name
60
+ params = [tzname]
61
+ else:
62
+ params = []
63
+ fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
64
+ format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
65
+ format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
66
+ try:
67
+ i = fields.index(lookup_type) + 1
68
+ except ValueError:
69
+ sql = field_name
70
+ else:
71
+ format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
72
+ sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
73
+ return sql, params
74
+
75
+ def date_interval_sql(self, timedelta):
76
+ return "INTERVAL '%d 0:0:%d:%d' DAY_MICROSECOND" % (
77
+ timedelta.days, timedelta.seconds, timedelta.microseconds), []
78
+
79
+ def format_for_duration_arithmetic(self, sql):
80
+ if self.connection.features.supports_microsecond_precision:
81
+ return 'INTERVAL %s MICROSECOND' % sql
82
+ else:
83
+ return 'INTERVAL FLOOR(%s / 1000000) SECOND' % sql
84
+
85
+ def drop_foreignkey_sql(self):
86
+ return "DROP FOREIGN KEY"
87
+
88
+ def force_no_ordering(self):
89
+ """
90
+ "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
91
+ columns. If no ordering would otherwise be applied, we don't want any
92
+ implicit sorting going on.
93
+ """
94
+ return [(None, ("NULL", [], False))]
95
+
96
+ def fulltext_search_sql(self, field_name):
97
+ return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name
98
+
99
+ def last_executed_query(self, cursor, sql, params):
100
+ # With MySQLdb, cursor objects have an (undocumented) "_last_executed"
101
+ # attribute where the exact query sent to the database is saved.
102
+ # See MySQLdb/cursors.py in the source distribution.
103
+ return force_text(getattr(cursor, '_last_executed', None), errors='replace')
104
+
105
+ def no_limit_value(self):
106
+ # 2**64 - 1, as recommended by the MySQL documentation
107
+ return 18446744073709551615
108
+
109
+ def quote_name(self, name):
110
+ if name.startswith("`") and name.endswith("`"):
111
+ return name # Quoting once is enough.
112
+ return "`%s`" % name
113
+
114
+ def random_function_sql(self):
115
+ return 'RAND()'
116
+
117
+ def sql_flush(self, style, tables, sequences, allow_cascade=False):
118
+ # NB: The generated SQL below is specific to MySQL
119
+ # 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements
120
+ # to clear all tables of all data
121
+ if tables:
122
+ sql = ['SET FOREIGN_KEY_CHECKS = 0;']
123
+ for table in tables:
124
+ sql.append('%s %s;' % (
125
+ style.SQL_KEYWORD('TRUNCATE'),
126
+ style.SQL_FIELD(self.quote_name(table)),
127
+ ))
128
+ sql.append('SET FOREIGN_KEY_CHECKS = 1;')
129
+ sql.extend(self.sequence_reset_by_name_sql(style, sequences))
130
+ return sql
131
+ else:
132
+ return []
133
+
134
+ def validate_autopk_value(self, value):
135
+ # MySQLism: zero in AUTO_INCREMENT field does not work. Refs #17653.
136
+ if value == 0:
137
+ raise ValueError('The database backend does not accept 0 as a '
138
+ 'value for AutoField.')
139
+ return value
140
+
141
+ def value_to_db_datetime(self, value):
142
+ if value is None:
143
+ return None
144
+
145
+ # MySQL doesn't support tz-aware datetimes
146
+ if timezone.is_aware(value):
147
+ if settings.USE_TZ:
148
+ value = value.astimezone(timezone.utc).replace(tzinfo=None)
149
+ else:
150
+ raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")
151
+
152
+ if not self.connection.features.supports_microsecond_precision:
153
+ value = value.replace(microsecond=0)
154
+
155
+ return six.text_type(value)
156
+
157
+ def value_to_db_time(self, value):
158
+ if value is None:
159
+ return None
160
+
161
+ # MySQL doesn't support tz-aware times
162
+ if timezone.is_aware(value):
163
+ raise ValueError("MySQL backend does not support timezone-aware times.")
164
+
165
+ return six.text_type(value)
166
+
167
+ def max_name_length(self):
168
+ return 64
169
+
170
+ def bulk_insert_sql(self, fields, num_values):
171
+ items_sql = "(%s)" % ", ".join(["%s"] * len(fields))
172
+ return "VALUES " + ", ".join([items_sql] * num_values)
173
+
174
+ def combine_expression(self, connector, sub_expressions):
175
+ """
176
+ MySQL requires special cases for ^ operators in query expressions
177
+ """
178
+ if connector == '^':
179
+ return 'POW(%s)' % ','.join(sub_expressions)
180
+ return super(DatabaseOperations, self).combine_expression(connector, sub_expressions)
181
+
182
+ def get_db_converters(self, expression):
183
+ converters = super(DatabaseOperations, self).get_db_converters(expression)
184
+ internal_type = expression.output_field.get_internal_type()
185
+ if internal_type in ['BooleanField', 'NullBooleanField']:
186
+ converters.append(self.convert_booleanfield_value)
187
+ if internal_type == 'UUIDField':
188
+ converters.append(self.convert_uuidfield_value)
189
+ if internal_type == 'TextField':
190
+ converters.append(self.convert_textfield_value)
191
+ return converters
192
+
193
+ def convert_booleanfield_value(self, value, expression, connection, context):
194
+ if value in (0, 1):
195
+ value = bool(value)
196
+ return value
197
+
198
+ def convert_uuidfield_value(self, value, expression, connection, context):
199
+ if value is not None:
200
+ value = uuid.UUID(value)
201
+ return value
202
+
203
+ def convert_textfield_value(self, value, expression, connection, context):
204
+ if value is not None:
205
+ value = force_text(value)
206
+ return value
@@ -0,0 +1,125 @@
1
+ from django.db.backends.base.schema import BaseDatabaseSchemaEditor
2
+ from django.db.models import NOT_PROVIDED
3
+
4
+
5
+ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
6
+
7
+ sql_rename_table = "RENAME TABLE %(old_table)s TO %(new_table)s"
8
+
9
+ sql_alter_column_null = "MODIFY %(column)s %(type)s NULL"
10
+ sql_alter_column_not_null = "MODIFY %(column)s %(type)s NOT NULL"
11
+ sql_alter_column_type = "MODIFY %(column)s %(type)s"
12
+ sql_rename_column = "ALTER TABLE %(table)s CHANGE %(old_column)s %(new_column)s %(type)s"
13
+
14
+ sql_delete_table = "DROP TABLE %(table)s"
15
+ sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s"
16
+ sql_delete_unique = "ALTER TABLE %(table)s DROP INDEX %(name)s"
17
+ sql_delete_index = "DROP INDEX %(name)s ON %(table)s"
18
+
19
+ alter_string_set_null = 'MODIFY %(column)s %(type)s NULL;'
20
+ alter_string_drop_null = 'MODIFY %(column)s %(type)s NOT NULL;'
21
+
22
+ sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
23
+ sql_delete_pk = "ALTER TABLE %(table)s DROP PRIMARY KEY"
24
+
25
+ def quote_value(self, value):
26
+ # Inner import to allow module to fail to load gracefully
27
+ import MySQLdb.converters
28
+ return MySQLdb.escape(value, MySQLdb.converters.conversions)
29
+
30
+ def skip_default(self, field):
31
+ """
32
+ MySQL doesn't accept default values for longtext and longblob
33
+ and implicitly treats these columns as nullable.
34
+ """
35
+ return field.db_type(self.connection) in {'longtext', 'longblob'}
36
+
37
+ def add_field(self, model, field):
38
+ super(DatabaseSchemaEditor, self).add_field(model, field)
39
+
40
+ # Simulate the effect of a one-off default.
41
+ # field.default may be unhashable, so a set isn't used for "in" check.
42
+ if self.skip_default(field) and field.default not in (None, NOT_PROVIDED):
43
+ effective_default = self.effective_default(field)
44
+ self.execute('UPDATE %(table)s SET %(column)s = %%s' % {
45
+ 'table': self.quote_name(model._meta.db_table),
46
+ 'column': self.quote_name(field.column),
47
+ }, [effective_default])
48
+
49
+ def _model_indexes_sql(self, model):
50
+ storage = self.connection.introspection.get_storage_engine(
51
+ self.connection.cursor(), model._meta.db_table
52
+ )
53
+ if storage == "InnoDB":
54
+ for field in model._meta.local_fields:
55
+ if field.db_index and not field.unique and field.get_internal_type() == "ForeignKey":
56
+ # Temporary setting db_index to False (in memory) to disable
57
+ # index creation for FKs (index automatically created by MySQL)
58
+ field.db_index = False
59
+ return super(DatabaseSchemaEditor, self)._model_indexes_sql(model)
60
+
61
+ def _delete_composed_index(self, model, fields, *args):
62
+ """
63
+ MySQL can remove an implicit FK index on a field when that field is
64
+ covered by another index like a unique_together. "covered" here means
65
+ that the more complex index starts like the simpler one.
66
+ http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757
67
+ We check here before removing the [unique|index]_together if we have to
68
+ recreate a FK index.
69
+ """
70
+ first_field = model._meta.get_field(fields[0])
71
+ if first_field.get_internal_type() == 'ForeignKey':
72
+ constraint_names = self._constraint_names(model, [first_field.column], index=True)
73
+ if not constraint_names:
74
+ self.execute(self._create_index_sql(model, [first_field], suffix=""))
75
+ return super(DatabaseSchemaEditor, self)._delete_composed_index(model, fields, *args)
76
+
77
+ def _set_field_new_type_null_status(self, field, new_type):
78
+ """
79
+ Keep the null property of the old field. If it has changed, it will be
80
+ handled separately.
81
+ """
82
+ if field.null:
83
+ new_type += " NULL"
84
+ else:
85
+ new_type += " NOT NULL"
86
+ return new_type
87
+
88
+ def _alter_column_type_sql(self, table, old_field, new_field, new_type):
89
+ new_type = self._set_field_new_type_null_status(old_field, new_type)
90
+ return super(DatabaseSchemaEditor, self)._alter_column_type_sql(table, old_field, new_field, new_type)
91
+
92
+ def _rename_field_sql(self, table, old_field, new_field, new_type):
93
+ new_type = self._set_field_new_type_null_status(old_field, new_type)
94
+ return super(DatabaseSchemaEditor, self)._rename_field_sql(table, old_field, new_field, new_type)
95
+
96
+ def remove_field(self, model, field):
97
+ """
98
+ Removes a field from a model. Usually involves deleting a column,
99
+ but for M2Ms may involve deleting a table.
100
+ """
101
+ # Special-case implicit M2M tables
102
+ if field.many_to_many and field.rel.through._meta.auto_created:
103
+ return self.delete_model(field.rel.through)
104
+ # It might not actually have a column behind it
105
+ if field.db_parameters(connection=self.connection)['type'] is None:
106
+ return
107
+ # Drop any FK constraints, MySQL requires explicit deletion
108
+ if field.rel:
109
+ fk_names = self._constraint_names(model, [field.column], foreign_key=True)
110
+ for fk_name in fk_names:
111
+ self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
112
+ # Drop any Index, TiDB requires explicite deletion
113
+ if field.db_index:
114
+ idx_names = self._constraint_names(model, [field.column], index=True)
115
+ for idx_name in idx_names:
116
+ self.execute(self._delete_constraint_sql(self.sql_delete_index, model, idx_name))
117
+ # Delete the column
118
+ sql = self.sql_delete_column % {
119
+ "table": self.quote_name(model._meta.db_table),
120
+ "column": self.quote_name(field.column),
121
+ }
122
+ self.execute(sql)
123
+ # Reset connection if required
124
+ if self.connection.features.connection_persists_old_columns:
125
+ self.connection.close()
@@ -0,0 +1,35 @@
1
+ from django.core import checks
2
+ from django.db.backends.base.validation import BaseDatabaseValidation
3
+
4
+
5
+ class DatabaseValidation(BaseDatabaseValidation):
6
+ def check_field(self, field, **kwargs):
7
+ """
8
+ MySQL has the following field length restriction:
9
+ No character (varchar) fields can have a length exceeding 255
10
+ characters if they have a unique index on them.
11
+ """
12
+ from django.db import connection
13
+
14
+ errors = super(DatabaseValidation, self).check_field(field, **kwargs)
15
+
16
+ # Ignore any related fields.
17
+ if getattr(field, 'rel', None) is None:
18
+ field_type = field.db_type(connection)
19
+
20
+ # Ignore any non-concrete fields
21
+ if field_type is None:
22
+ return errors
23
+
24
+ if (field_type.startswith('varchar') # Look for CharFields...
25
+ and field.unique # ... that are unique
26
+ and (field.max_length is None or int(field.max_length) > 255)):
27
+ errors.append(
28
+ checks.Error(
29
+ ('MySQL does not allow unique CharFields to have a max_length > 255.'),
30
+ hint=None,
31
+ obj=field,
32
+ id='mysql.E001',
33
+ )
34
+ )
35
+ return errors
@@ -0,0 +1,2 @@
1
+ [metadata]
2
+ description-file = README.md
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env python
2
+
3
+ from distutils.core import setup
4
+
5
+ long_description = """TiDB backend for Django"""
6
+
7
+ setup(
8
+ name='django_tidb',
9
+ version='1.0',
10
+ author='Rain Li',
11
+ author_email='blacktear23@gmail.com',
12
+ url='http://github.com/blacktear23/django_tidb',
13
+ download_url='http://github.com/blackear23/django_tidb/archive/1.0.tar.gz',
14
+ description='TiDB backend for Django',
15
+ long_description=long_description,
16
+ keywords=['django', 'tidb'],
17
+ packages=['django_tidb', 'django_tidb.tidb'],
18
+ license='Apache2',
19
+ classifiers=[
20
+ 'Development Status :: 4 - Beta',
21
+ 'Intended Audience :: Developers',
22
+ 'Operating System :: OS Independent',
23
+ 'Programming Language :: Python :: 2',
24
+ 'Topic :: Software Development :: Libraries',
25
+ ],
26
+ )