db.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. "Database cache backend."
  2. import base64
  3. import pickle
  4. from datetime import datetime
  5. from django.conf import settings
  6. from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
  7. from django.db import DatabaseError, connections, models, router, transaction
  8. from django.utils import timezone
  9. class Options:
  10. """A class that will quack like a Django model _meta class.
  11. This allows cache operations to be controlled by the router
  12. """
  13. def __init__(self, table):
  14. self.db_table = table
  15. self.app_label = 'django_cache'
  16. self.model_name = 'cacheentry'
  17. self.verbose_name = 'cache entry'
  18. self.verbose_name_plural = 'cache entries'
  19. self.object_name = 'CacheEntry'
  20. self.abstract = False
  21. self.managed = True
  22. self.proxy = False
  23. self.swapped = False
  24. class BaseDatabaseCache(BaseCache):
  25. def __init__(self, table, params):
  26. super().__init__(params)
  27. self._table = table
  28. class CacheEntry:
  29. _meta = Options(table)
  30. self.cache_model_class = CacheEntry
  31. class DatabaseCache(BaseDatabaseCache):
  32. # This class uses cursors provided by the database connection. This means
  33. # it reads expiration values as aware or naive datetimes, depending on the
  34. # value of USE_TZ and whether the database supports time zones. The ORM's
  35. # conversion and adaptation infrastructure is then used to avoid comparing
  36. # aware and naive datetimes accidentally.
  37. pickle_protocol = pickle.HIGHEST_PROTOCOL
  38. def get(self, key, default=None, version=None):
  39. return self.get_many([key], version).get(key, default)
  40. def get_many(self, keys, version=None):
  41. if not keys:
  42. return {}
  43. key_map = {self.make_and_validate_key(key, version=version): key for key in keys}
  44. db = router.db_for_read(self.cache_model_class)
  45. connection = connections[db]
  46. quote_name = connection.ops.quote_name
  47. table = quote_name(self._table)
  48. with connection.cursor() as cursor:
  49. cursor.execute(
  50. 'SELECT %s, %s, %s FROM %s WHERE %s IN (%s)' % (
  51. quote_name('cache_key'),
  52. quote_name('value'),
  53. quote_name('expires'),
  54. table,
  55. quote_name('cache_key'),
  56. ', '.join(['%s'] * len(key_map)),
  57. ),
  58. list(key_map),
  59. )
  60. rows = cursor.fetchall()
  61. result = {}
  62. expired_keys = []
  63. expression = models.Expression(output_field=models.DateTimeField())
  64. converters = (connection.ops.get_db_converters(expression) + expression.get_db_converters(connection))
  65. for key, value, expires in rows:
  66. for converter in converters:
  67. expires = converter(expires, expression, connection)
  68. if expires < timezone.now():
  69. expired_keys.append(key)
  70. else:
  71. value = connection.ops.process_clob(value)
  72. value = pickle.loads(base64.b64decode(value.encode()))
  73. result[key_map.get(key)] = value
  74. self._base_delete_many(expired_keys)
  75. return result
  76. def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
  77. key = self.make_and_validate_key(key, version=version)
  78. self._base_set('set', key, value, timeout)
  79. def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
  80. key = self.make_and_validate_key(key, version=version)
  81. return self._base_set('add', key, value, timeout)
  82. def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):
  83. key = self.make_and_validate_key(key, version=version)
  84. return self._base_set('touch', key, None, timeout)
  85. def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
  86. timeout = self.get_backend_timeout(timeout)
  87. db = router.db_for_write(self.cache_model_class)
  88. connection = connections[db]
  89. quote_name = connection.ops.quote_name
  90. table = quote_name(self._table)
  91. with connection.cursor() as cursor:
  92. cursor.execute("SELECT COUNT(*) FROM %s" % table)
  93. num = cursor.fetchone()[0]
  94. now = timezone.now()
  95. now = now.replace(microsecond=0)
  96. if timeout is None:
  97. exp = datetime.max
  98. else:
  99. tz = timezone.utc if settings.USE_TZ else None
  100. exp = datetime.fromtimestamp(timeout, tz=tz)
  101. exp = exp.replace(microsecond=0)
  102. if num > self._max_entries:
  103. self._cull(db, cursor, now, num)
  104. pickled = pickle.dumps(value, self.pickle_protocol)
  105. # The DB column is expecting a string, so make sure the value is a
  106. # string, not bytes. Refs #19274.
  107. b64encoded = base64.b64encode(pickled).decode('latin1')
  108. try:
  109. # Note: typecasting for datetimes is needed by some 3rd party
  110. # database backends. All core backends work without typecasting,
  111. # so be careful about changes here - test suite will NOT pick
  112. # regressions.
  113. with transaction.atomic(using=db):
  114. cursor.execute(
  115. 'SELECT %s, %s FROM %s WHERE %s = %%s' % (
  116. quote_name('cache_key'),
  117. quote_name('expires'),
  118. table,
  119. quote_name('cache_key'),
  120. ),
  121. [key]
  122. )
  123. result = cursor.fetchone()
  124. if result:
  125. current_expires = result[1]
  126. expression = models.Expression(output_field=models.DateTimeField())
  127. for converter in (connection.ops.get_db_converters(expression) +
  128. expression.get_db_converters(connection)):
  129. current_expires = converter(current_expires, expression, connection)
  130. exp = connection.ops.adapt_datetimefield_value(exp)
  131. if result and mode == 'touch':
  132. cursor.execute(
  133. 'UPDATE %s SET %s = %%s WHERE %s = %%s' % (
  134. table,
  135. quote_name('expires'),
  136. quote_name('cache_key')
  137. ),
  138. [exp, key]
  139. )
  140. elif result and (mode == 'set' or (mode == 'add' and current_expires < now)):
  141. cursor.execute(
  142. 'UPDATE %s SET %s = %%s, %s = %%s WHERE %s = %%s' % (
  143. table,
  144. quote_name('value'),
  145. quote_name('expires'),
  146. quote_name('cache_key'),
  147. ),
  148. [b64encoded, exp, key]
  149. )
  150. elif mode != 'touch':
  151. cursor.execute(
  152. 'INSERT INTO %s (%s, %s, %s) VALUES (%%s, %%s, %%s)' % (
  153. table,
  154. quote_name('cache_key'),
  155. quote_name('value'),
  156. quote_name('expires'),
  157. ),
  158. [key, b64encoded, exp]
  159. )
  160. else:
  161. return False # touch failed.
  162. except DatabaseError:
  163. # To be threadsafe, updates/inserts are allowed to fail silently
  164. return False
  165. else:
  166. return True
  167. def delete(self, key, version=None):
  168. key = self.make_and_validate_key(key, version=version)
  169. return self._base_delete_many([key])
  170. def delete_many(self, keys, version=None):
  171. keys = [self.make_and_validate_key(key, version=version) for key in keys]
  172. self._base_delete_many(keys)
  173. def _base_delete_many(self, keys):
  174. if not keys:
  175. return False
  176. db = router.db_for_write(self.cache_model_class)
  177. connection = connections[db]
  178. quote_name = connection.ops.quote_name
  179. table = quote_name(self._table)
  180. with connection.cursor() as cursor:
  181. cursor.execute(
  182. 'DELETE FROM %s WHERE %s IN (%s)' % (
  183. table,
  184. quote_name('cache_key'),
  185. ', '.join(['%s'] * len(keys)),
  186. ),
  187. keys,
  188. )
  189. return bool(cursor.rowcount)
  190. def has_key(self, key, version=None):
  191. key = self.make_and_validate_key(key, version=version)
  192. db = router.db_for_read(self.cache_model_class)
  193. connection = connections[db]
  194. quote_name = connection.ops.quote_name
  195. now = timezone.now().replace(microsecond=0, tzinfo=None)
  196. with connection.cursor() as cursor:
  197. cursor.execute(
  198. 'SELECT %s FROM %s WHERE %s = %%s and expires > %%s' % (
  199. quote_name('cache_key'),
  200. quote_name(self._table),
  201. quote_name('cache_key'),
  202. ),
  203. [key, connection.ops.adapt_datetimefield_value(now)]
  204. )
  205. return cursor.fetchone() is not None
  206. def _cull(self, db, cursor, now, num):
  207. if self._cull_frequency == 0:
  208. self.clear()
  209. else:
  210. connection = connections[db]
  211. table = connection.ops.quote_name(self._table)
  212. cursor.execute("DELETE FROM %s WHERE expires < %%s" % table,
  213. [connection.ops.adapt_datetimefield_value(now)])
  214. deleted_count = cursor.rowcount
  215. remaining_num = num - deleted_count
  216. if remaining_num > self._max_entries:
  217. cull_num = remaining_num // self._cull_frequency
  218. cursor.execute(
  219. connection.ops.cache_key_culling_sql() % table,
  220. [cull_num])
  221. last_cache_key = cursor.fetchone()
  222. if last_cache_key:
  223. cursor.execute(
  224. 'DELETE FROM %s WHERE cache_key < %%s' % table,
  225. [last_cache_key[0]],
  226. )
  227. def clear(self):
  228. db = router.db_for_write(self.cache_model_class)
  229. connection = connections[db]
  230. table = connection.ops.quote_name(self._table)
  231. with connection.cursor() as cursor:
  232. cursor.execute('DELETE FROM %s' % table)