utils.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import pkgutil
  2. from importlib import import_module
  3. from django.conf import settings
  4. from django.core.exceptions import ImproperlyConfigured
  5. # For backwards compatibility with Django < 3.2
  6. from django.utils.connection import ConnectionDoesNotExist # NOQA: F401
  7. from django.utils.connection import BaseConnectionHandler
  8. from django.utils.functional import cached_property
  9. from django.utils.module_loading import import_string
  10. DEFAULT_DB_ALIAS = "default"
  11. DJANGO_VERSION_PICKLE_KEY = "_django_version"
  12. class Error(Exception):
  13. pass
  14. class InterfaceError(Error):
  15. pass
  16. class DatabaseError(Error):
  17. pass
  18. class DataError(DatabaseError):
  19. pass
  20. class OperationalError(DatabaseError):
  21. pass
  22. class IntegrityError(DatabaseError):
  23. pass
  24. class InternalError(DatabaseError):
  25. pass
  26. class ProgrammingError(DatabaseError):
  27. pass
  28. class NotSupportedError(DatabaseError):
  29. pass
  30. class DatabaseErrorWrapper:
  31. """
  32. Context manager and decorator that reraises backend-specific database
  33. exceptions using Django's common wrappers.
  34. """
  35. def __init__(self, wrapper):
  36. """
  37. wrapper is a database wrapper.
  38. It must have a Database attribute defining PEP-249 exceptions.
  39. """
  40. self.wrapper = wrapper
  41. def __del__(self):
  42. del self.wrapper
  43. def __enter__(self):
  44. pass
  45. def __exit__(self, exc_type, exc_value, traceback):
  46. if exc_type is None:
  47. return
  48. for dj_exc_type in (
  49. DataError,
  50. OperationalError,
  51. IntegrityError,
  52. InternalError,
  53. ProgrammingError,
  54. NotSupportedError,
  55. DatabaseError,
  56. InterfaceError,
  57. Error,
  58. ):
  59. db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
  60. if issubclass(exc_type, db_exc_type):
  61. dj_exc_value = dj_exc_type(*exc_value.args)
  62. # Only set the 'errors_occurred' flag for errors that may make
  63. # the connection unusable.
  64. if dj_exc_type not in (DataError, IntegrityError):
  65. self.wrapper.errors_occurred = True
  66. raise dj_exc_value.with_traceback(traceback) from exc_value
  67. def __call__(self, func):
  68. # Note that we are intentionally not using @wraps here for performance
  69. # reasons. Refs #21109.
  70. def inner(*args, **kwargs):
  71. with self:
  72. return func(*args, **kwargs)
  73. return inner
  74. def load_backend(backend_name):
  75. """
  76. Return a database backend's "base" module given a fully qualified database
  77. backend name, or raise an error if it doesn't exist.
  78. """
  79. # This backend was renamed in Django 1.9.
  80. if backend_name == "django.db.backends.postgresql_psycopg2":
  81. backend_name = "django.db.backends.postgresql"
  82. try:
  83. return import_module("%s.base" % backend_name)
  84. except ImportError as e_user:
  85. # The database backend wasn't found. Display a helpful error message
  86. # listing all built-in database backends.
  87. import django.db.backends
  88. builtin_backends = [
  89. name
  90. for _, name, ispkg in pkgutil.iter_modules(django.db.backends.__path__)
  91. if ispkg and name not in {"base", "dummy"}
  92. ]
  93. if backend_name not in ["django.db.backends.%s" % b for b in builtin_backends]:
  94. backend_reprs = map(repr, sorted(builtin_backends))
  95. raise ImproperlyConfigured(
  96. "%r isn't an available database backend or couldn't be "
  97. "imported. Check the above exception. To use one of the "
  98. "built-in backends, use 'django.db.backends.XXX', where XXX "
  99. "is one of:\n"
  100. " %s" % (backend_name, ", ".join(backend_reprs))
  101. ) from e_user
  102. else:
  103. # If there's some other error, this must be an error in Django
  104. raise
  105. class ConnectionHandler(BaseConnectionHandler):
  106. settings_name = "DATABASES"
  107. # Connections needs to still be an actual thread local, as it's truly
  108. # thread-critical. Database backends should use @async_unsafe to protect
  109. # their code from async contexts, but this will give those contexts
  110. # separate connections in case it's needed as well. There's no cleanup
  111. # after async contexts, though, so we don't allow that if we can help it.
  112. thread_critical = True
  113. def configure_settings(self, databases):
  114. databases = super().configure_settings(databases)
  115. if databases == {}:
  116. databases[DEFAULT_DB_ALIAS] = {"ENGINE": "django.db.backends.dummy"}
  117. elif DEFAULT_DB_ALIAS not in databases:
  118. raise ImproperlyConfigured(
  119. f"You must define a '{DEFAULT_DB_ALIAS}' database."
  120. )
  121. elif databases[DEFAULT_DB_ALIAS] == {}:
  122. databases[DEFAULT_DB_ALIAS]["ENGINE"] = "django.db.backends.dummy"
  123. # Configure default settings.
  124. for conn in databases.values():
  125. conn.setdefault("ATOMIC_REQUESTS", False)
  126. conn.setdefault("AUTOCOMMIT", True)
  127. conn.setdefault("ENGINE", "django.db.backends.dummy")
  128. if conn["ENGINE"] == "django.db.backends." or not conn["ENGINE"]:
  129. conn["ENGINE"] = "django.db.backends.dummy"
  130. conn.setdefault("CONN_MAX_AGE", 0)
  131. conn.setdefault("CONN_HEALTH_CHECKS", False)
  132. conn.setdefault("OPTIONS", {})
  133. conn.setdefault("TIME_ZONE", None)
  134. for setting in ["NAME", "USER", "PASSWORD", "HOST", "PORT"]:
  135. conn.setdefault(setting, "")
  136. test_settings = conn.setdefault("TEST", {})
  137. default_test_settings = [
  138. ("CHARSET", None),
  139. ("COLLATION", None),
  140. ("MIGRATE", True),
  141. ("MIRROR", None),
  142. ("NAME", None),
  143. ]
  144. for key, value in default_test_settings:
  145. test_settings.setdefault(key, value)
  146. return databases
  147. @property
  148. def databases(self):
  149. # Maintained for backward compatibility as some 3rd party packages have
  150. # made use of this private API in the past. It is no longer used within
  151. # Django itself.
  152. return self.settings
  153. def create_connection(self, alias):
  154. db = self.settings[alias]
  155. backend = load_backend(db["ENGINE"])
  156. return backend.DatabaseWrapper(db, alias)
  157. class ConnectionRouter:
  158. def __init__(self, routers=None):
  159. """
  160. If routers is not specified, default to settings.DATABASE_ROUTERS.
  161. """
  162. self._routers = routers
  163. @cached_property
  164. def routers(self):
  165. if self._routers is None:
  166. self._routers = settings.DATABASE_ROUTERS
  167. routers = []
  168. for r in self._routers:
  169. if isinstance(r, str):
  170. router = import_string(r)()
  171. else:
  172. router = r
  173. routers.append(router)
  174. return routers
  175. def _router_func(action):
  176. def _route_db(self, model, **hints):
  177. chosen_db = None
  178. for router in self.routers:
  179. try:
  180. method = getattr(router, action)
  181. except AttributeError:
  182. # If the router doesn't have a method, skip to the next
  183. # one.
  184. pass
  185. else:
  186. chosen_db = method(model, **hints)
  187. if chosen_db:
  188. return chosen_db
  189. instance = hints.get("instance")
  190. if instance is not None and instance._state.db:
  191. return instance._state.db
  192. return DEFAULT_DB_ALIAS
  193. return _route_db
  194. db_for_read = _router_func("db_for_read")
  195. db_for_write = _router_func("db_for_write")
  196. def allow_relation(self, obj1, obj2, **hints):
  197. for router in self.routers:
  198. try:
  199. method = router.allow_relation
  200. except AttributeError:
  201. # If the router doesn't have a method, skip to the next one.
  202. pass
  203. else:
  204. allow = method(obj1, obj2, **hints)
  205. if allow is not None:
  206. return allow
  207. return obj1._state.db == obj2._state.db
  208. def allow_migrate(self, db, app_label, **hints):
  209. for router in self.routers:
  210. try:
  211. method = router.allow_migrate
  212. except AttributeError:
  213. # If the router doesn't have a method, skip to the next one.
  214. continue
  215. allow = method(db, app_label, **hints)
  216. if allow is not None:
  217. return allow
  218. return True
  219. def allow_migrate_model(self, db, model):
  220. return self.allow_migrate(
  221. db,
  222. model._meta.app_label,
  223. model_name=model._meta.model_name,
  224. model=model,
  225. )
  226. def get_migratable_models(self, app_config, db, include_auto_created=False):
  227. """Return app models allowed to be migrated on provided db."""
  228. models = app_config.get_models(include_auto_created=include_auto_created)
  229. return [model for model in models if self.allow_migrate_model(db, model)]