Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validation.py 2.5KB

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