validation.py 2.9 KB

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