utils.py 10.0 KB

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