| 1 |
from django.core import checks |
| 2 |
from django.db.backends.base.validation import BaseDatabaseValidation |
| 3 |
from django.utils.version import get_docs_version |
| 4 |
|
| 5 |
|
| 6 |
class DatabaseValidation(BaseDatabaseValidation): |
| 7 |
def check(self, **kwargs): |
| 8 |
issues = super().check(**kwargs) |
| 9 |
issues.extend(self._check_sql_mode(**kwargs)) |
| 10 |
return issues |
| 11 |
|
| 12 |
def _check_sql_mode(self, **kwargs): |
| 13 |
if not ( |
| 14 |
self.connection.sql_mode & {"STRICT_TRANS_TABLES", "STRICT_ALL_TABLES"} |
| 15 |
): |
| 16 |
return [ |
| 17 |
checks.Warning( |
| 18 |
"%s Strict Mode is not set for database connection '%s'" |
| 19 |
% (self.connection.display_name, self.connection.alias), |
| 20 |
hint=( |
| 21 |
"%s's Strict Mode fixes many data integrity problems in " |
| 22 |
"%s, such as data truncation upon insertion, by " |
| 23 |
"escalating warnings into errors. It is strongly " |
| 24 |
"recommended you activate it. See: " |
| 25 |
"https://docs.djangoproject.com/en/%s/ref/databases/" |
| 26 |
"#mysql-sql-mode" |
| 27 |
% ( |
| 28 |
self.connection.display_name, |
| 29 |
self.connection.display_name, |
| 30 |
get_docs_version(), |
| 31 |
), |
| 32 |
), |
| 33 |
id="mysql.W002", |
| 34 |
) |
| 35 |
] |
| 36 |
return [] |
| 37 |
|
| 38 |
def check_field_type(self, field, field_type): |
| 39 |
""" |
| 40 |
MySQL has the following field length restriction: |
| 41 |
No character (varchar) fields can have a length exceeding 255 |
| 42 |
characters if they have a unique index on them. |
| 43 |
MySQL doesn't support a database index on some data types. |
| 44 |
""" |
| 45 |
errors = [] |
| 46 |
if ( |
| 47 |
field_type.startswith("varchar") |
| 48 |
and field.unique |
| 49 |
and (field.max_length is None or int(field.max_length) > 255) |
| 50 |
): |
| 51 |
errors.append( |
| 52 |
checks.Warning( |
| 53 |
"%s may not allow unique CharFields to have a max_length " |
| 54 |
"> 255." % self.connection.display_name, |
| 55 |
obj=field, |
| 56 |
hint=( |
| 57 |
"See: https://docs.djangoproject.com/en/%s/ref/" |
| 58 |
"databases/#mysql-character-fields" % get_docs_version() |
| 59 |
), |
| 60 |
id="mysql.W003", |
| 61 |
) |
| 62 |
) |
| 63 |
|
| 64 |
if field.db_index and field_type.lower() in self.connection._limited_data_types: |
| 65 |
errors.append( |
| 66 |
checks.Warning( |
| 67 |
"%s does not support a database index on %s columns." |
| 68 |
% (self.connection.display_name, field_type), |
| 69 |
hint=( |
| 70 |
"An index won't be created. Silence this warning if " |
| 71 |
"you don't care about it." |
| 72 |
), |
| 73 |
obj=field, |
| 74 |
id="fields.W162", |
| 75 |
) |
| 76 |
) |
| 77 |
return errors |