validation.py 3.0 KB

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