db.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. from django.utils.encoding import force_bytes
  10. from django.utils.inspect import func_supports_parameter
  11. class Options:
  12. """A class that will quack like a Django model _meta class.
  13. This allows cache operations to be controlled by the router
  14. """
  15. def __init__(self, table):
  16. self.db_table = table
  17. self.app_label = 'django_cache'
  18. self.model_name = 'cacheentry'
  19. self.verbose_name = 'cache entry'
  20. self.verbose_name_plural = 'cache entries'
  21. self.object_name = 'CacheEntry'
  22. self.abstract = False
  23. self.managed = True
  24. self.proxy = False
  25. self.swapped = False
  26. class BaseDatabaseCache(BaseCache):
  27. def __init__(self, table, params):
  28. BaseCache.__init__(self, params)
  29. self._table = table
  30. class CacheEntry:
  31. _meta = Options(table)
  32. self.cache_model_class = CacheEntry
  33. class DatabaseCache(BaseDatabaseCache):
  34. # This class uses cursors provided by the database connection. This means
  35. # it reads expiration values as aware or naive datetimes, depending on the
  36. # value of USE_TZ and whether the database supports time zones. The ORM's
  37. # conversion and adaptation infrastructure is then used to avoid comparing
  38. # aware and naive datetimes accidentally.
  39. def get(self, key, default=None, version=None):
  40. key = self.make_key(key, version=version)
  41. self.validate_key(key)
  42. db = router.db_for_read(self.cache_model_class)
  43. connection = connections[db]
  44. table = connection.ops.quote_name(self._table)
  45. with connection.cursor() as cursor:
  46. cursor.execute("SELECT cache_key, value, expires FROM %s "
  47. "WHERE cache_key = %%s" % table, [key])
  48. row = cursor.fetchone()
  49. if row is None:
  50. return default
  51. expires = row[2]
  52. expression = models.Expression(output_field=models.DateTimeField())
  53. for converter in (connection.ops.get_db_converters(expression) +
  54. expression.get_db_converters(connection)):
  55. if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning
  56. expires = converter(expires, expression, connection, {})
  57. else:
  58. expires = converter(expires, expression, connection)
  59. if expires < timezone.now():
  60. db = router.db_for_write(self.cache_model_class)
  61. connection = connections[db]
  62. with connection.cursor() as cursor:
  63. cursor.execute("DELETE FROM %s "
  64. "WHERE cache_key = %%s" % table, [key])
  65. return default
  66. value = connection.ops.process_clob(row[1])
  67. return pickle.loads(base64.b64decode(force_bytes(value)))
  68. def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
  69. key = self.make_key(key, version=version)
  70. self.validate_key(key)
  71. self._base_set('set', key, value, timeout)
  72. def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
  73. key = self.make_key(key, version=version)
  74. self.validate_key(key)
  75. return self._base_set('add', key, value, timeout)
  76. def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
  77. timeout = self.get_backend_timeout(timeout)
  78. db = router.db_for_write(self.cache_model_class)
  79. connection = connections[db]
  80. table = connection.ops.quote_name(self._table)
  81. with connection.cursor() as cursor:
  82. cursor.execute("SELECT COUNT(*) FROM %s" % table)
  83. num = cursor.fetchone()[0]
  84. now = timezone.now()
  85. now = now.replace(microsecond=0)
  86. if timeout is None:
  87. exp = datetime.max
  88. elif settings.USE_TZ:
  89. exp = datetime.utcfromtimestamp(timeout)
  90. else:
  91. exp = datetime.fromtimestamp(timeout)
  92. exp = exp.replace(microsecond=0)
  93. if num > self._max_entries:
  94. self._cull(db, cursor, now)
  95. pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
  96. # The DB column is expecting a string, so make sure the value is a
  97. # string, not bytes. Refs #19274.
  98. b64encoded = base64.b64encode(pickled).decode('latin1')
  99. try:
  100. # Note: typecasting for datetimes is needed by some 3rd party
  101. # database backends. All core backends work without typecasting,
  102. # so be careful about changes here - test suite will NOT pick
  103. # regressions.
  104. with transaction.atomic(using=db):
  105. cursor.execute("SELECT cache_key, expires FROM %s "
  106. "WHERE cache_key = %%s" % table, [key])
  107. result = cursor.fetchone()
  108. if result:
  109. current_expires = result[1]
  110. expression = models.Expression(output_field=models.DateTimeField())
  111. for converter in (connection.ops.get_db_converters(expression) +
  112. expression.get_db_converters(connection)):
  113. if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning
  114. current_expires = converter(current_expires, expression, connection, {})
  115. else:
  116. current_expires = converter(current_expires, expression, connection)
  117. exp = connection.ops.adapt_datetimefield_value(exp)
  118. if result and (mode == 'set' or (mode == 'add' and current_expires < now)):
  119. cursor.execute("UPDATE %s SET value = %%s, expires = %%s "
  120. "WHERE cache_key = %%s" % table,
  121. [b64encoded, exp, key])
  122. else:
  123. cursor.execute("INSERT INTO %s (cache_key, value, expires) "
  124. "VALUES (%%s, %%s, %%s)" % table,
  125. [key, b64encoded, exp])
  126. except DatabaseError:
  127. # To be threadsafe, updates/inserts are allowed to fail silently
  128. return False
  129. else:
  130. return True
  131. def delete(self, key, version=None):
  132. key = self.make_key(key, version=version)
  133. self.validate_key(key)
  134. db = router.db_for_write(self.cache_model_class)
  135. connection = connections[db]
  136. table = connection.ops.quote_name(self._table)
  137. with connection.cursor() as cursor:
  138. cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key])
  139. def has_key(self, key, version=None):
  140. key = self.make_key(key, version=version)
  141. self.validate_key(key)
  142. db = router.db_for_read(self.cache_model_class)
  143. connection = connections[db]
  144. table = connection.ops.quote_name(self._table)
  145. if settings.USE_TZ:
  146. now = datetime.utcnow()
  147. else:
  148. now = datetime.now()
  149. now = now.replace(microsecond=0)
  150. with connection.cursor() as cursor:
  151. cursor.execute("SELECT cache_key FROM %s "
  152. "WHERE cache_key = %%s and expires > %%s" % table,
  153. [key, connection.ops.adapt_datetimefield_value(now)])
  154. return cursor.fetchone() is not None
  155. def _cull(self, db, cursor, now):
  156. if self._cull_frequency == 0:
  157. self.clear()
  158. else:
  159. connection = connections[db]
  160. table = connection.ops.quote_name(self._table)
  161. cursor.execute("DELETE FROM %s WHERE expires < %%s" % table,
  162. [connection.ops.adapt_datetimefield_value(now)])
  163. cursor.execute("SELECT COUNT(*) FROM %s" % table)
  164. num = cursor.fetchone()[0]
  165. if num > self._max_entries:
  166. cull_num = num // self._cull_frequency
  167. cursor.execute(
  168. connection.ops.cache_key_culling_sql() % table,
  169. [cull_num])
  170. cursor.execute("DELETE FROM %s "
  171. "WHERE cache_key < %%s" % table,
  172. [cursor.fetchone()[0]])
  173. def clear(self):
  174. db = router.db_for_write(self.cache_model_class)
  175. connection = connections[db]
  176. table = connection.ops.quote_name(self._table)
  177. with connection.cursor() as cursor:
  178. cursor.execute('DELETE FROM %s' % table)