2006-02-24 14:07:01 +08:00
|
|
|
"Database cache backend."
|
2011-07-13 17:35:51 +08:00
|
|
|
import base64
|
2017-01-07 19:11:46 +08:00
|
|
|
import pickle
|
2006-02-24 14:07:01 +08:00
|
|
|
from datetime import datetime
|
2011-07-13 17:35:51 +08:00
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.conf import settings
|
|
|
|
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
|
2015-05-03 04:25:57 +08:00
|
|
|
from django.db import DatabaseError, connections, models, router, transaction
|
2016-12-01 18:38:01 +08:00
|
|
|
from django.utils import timezone
|
2017-07-07 01:18:05 +08:00
|
|
|
from django.utils.inspect import func_supports_parameter
|
2015-01-28 20:35:27 +08:00
|
|
|
|
2011-07-13 17:35:51 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Options:
|
2010-08-05 10:13:32 +08:00
|
|
|
"""A class that will quack like a Django model _meta class.
|
|
|
|
|
|
|
|
This allows cache operations to be controlled by the router
|
|
|
|
"""
|
|
|
|
def __init__(self, table):
|
|
|
|
self.db_table = table
|
|
|
|
self.app_label = 'django_cache'
|
2013-02-05 17:16:07 +08:00
|
|
|
self.model_name = 'cacheentry'
|
2010-08-05 10:13:32 +08:00
|
|
|
self.verbose_name = 'cache entry'
|
|
|
|
self.verbose_name_plural = 'cache entries'
|
2013-03-12 05:16:37 +08:00
|
|
|
self.object_name = 'CacheEntry'
|
2010-08-05 10:13:32 +08:00
|
|
|
self.abstract = False
|
|
|
|
self.managed = True
|
|
|
|
self.proxy = False
|
2015-02-19 15:27:58 +08:00
|
|
|
self.swapped = False
|
2010-08-05 10:13:32 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2010-12-21 23:19:19 +08:00
|
|
|
class BaseDatabaseCache(BaseCache):
|
|
|
|
def __init__(self, table, params):
|
2017-12-07 22:10:32 +08:00
|
|
|
super().__init__(params)
|
2010-08-05 10:13:32 +08:00
|
|
|
self._table = table
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class CacheEntry:
|
2010-08-05 10:13:32 +08:00
|
|
|
_meta = Options(table)
|
|
|
|
self.cache_model_class = CacheEntry
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2010-12-21 23:19:19 +08:00
|
|
|
class DatabaseCache(BaseDatabaseCache):
|
2011-11-20 18:17:12 +08:00
|
|
|
|
|
|
|
# This class uses cursors provided by the database connection. This means
|
2015-05-03 04:25:57 +08:00
|
|
|
# it reads expiration values as aware or naive datetimes, depending on the
|
|
|
|
# value of USE_TZ and whether the database supports time zones. The ORM's
|
|
|
|
# conversion and adaptation infrastructure is then used to avoid comparing
|
|
|
|
# aware and naive datetimes accidentally.
|
2011-11-20 18:17:12 +08:00
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
def get(self, key, default=None, version=None):
|
|
|
|
key = self.make_key(key, version=version)
|
2010-09-13 02:45:26 +08:00
|
|
|
self.validate_key(key)
|
2010-08-05 10:13:32 +08:00
|
|
|
db = router.db_for_read(self.cache_model_class)
|
2015-05-03 04:25:57 +08:00
|
|
|
connection = connections[db]
|
2018-03-14 10:46:41 +08:00
|
|
|
quote_name = connection.ops.quote_name
|
|
|
|
table = quote_name(self._table)
|
2010-08-05 10:13:32 +08:00
|
|
|
|
2015-05-03 04:25:57 +08:00
|
|
|
with connection.cursor() as cursor:
|
2018-03-14 10:46:41 +08:00
|
|
|
cursor.execute(
|
|
|
|
'SELECT %s, %s, %s FROM %s WHERE %s = %%s' % (
|
|
|
|
quote_name('cache_key'),
|
|
|
|
quote_name('value'),
|
|
|
|
quote_name('expires'),
|
|
|
|
table,
|
|
|
|
quote_name('cache_key'),
|
|
|
|
),
|
|
|
|
[key]
|
|
|
|
)
|
2014-01-09 23:05:15 +08:00
|
|
|
row = cursor.fetchone()
|
2006-02-24 14:07:01 +08:00
|
|
|
if row is None:
|
|
|
|
return default
|
2015-05-03 04:25:57 +08:00
|
|
|
|
2013-09-23 23:04:48 +08:00
|
|
|
expires = row[2]
|
2015-05-03 04:25:57 +08:00
|
|
|
expression = models.Expression(output_field=models.DateTimeField())
|
|
|
|
for converter in (connection.ops.get_db_converters(expression) +
|
|
|
|
expression.get_db_converters(connection)):
|
2017-07-07 01:18:05 +08:00
|
|
|
if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning
|
|
|
|
expires = converter(expires, expression, connection, {})
|
|
|
|
else:
|
|
|
|
expires = converter(expires, expression, connection)
|
2015-05-03 04:25:57 +08:00
|
|
|
|
|
|
|
if expires < timezone.now():
|
2010-08-05 10:13:32 +08:00
|
|
|
db = router.db_for_write(self.cache_model_class)
|
2015-05-03 04:25:57 +08:00
|
|
|
connection = connections[db]
|
|
|
|
with connection.cursor() as cursor:
|
2018-03-14 10:46:41 +08:00
|
|
|
cursor.execute(
|
|
|
|
'DELETE FROM %s WHERE %s = %%s' % (
|
|
|
|
table,
|
|
|
|
quote_name('cache_key'),
|
|
|
|
),
|
|
|
|
[key]
|
|
|
|
)
|
2006-02-24 14:07:01 +08:00
|
|
|
return default
|
2015-05-03 04:25:57 +08:00
|
|
|
|
|
|
|
value = connection.ops.process_clob(row[1])
|
2018-02-02 15:57:58 +08:00
|
|
|
return pickle.loads(base64.b64decode(value.encode()))
|
2006-02-24 14:07:01 +08:00
|
|
|
|
2013-05-18 18:54:59 +08:00
|
|
|
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
|
2010-11-19 23:39:35 +08:00
|
|
|
key = self.make_key(key, version=version)
|
2010-09-13 02:45:26 +08:00
|
|
|
self.validate_key(key)
|
2008-08-10 11:52:21 +08:00
|
|
|
self._base_set('set', key, value, timeout)
|
2007-10-20 23:16:34 +08:00
|
|
|
|
2013-05-18 18:54:59 +08:00
|
|
|
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
|
2010-11-19 23:39:35 +08:00
|
|
|
key = self.make_key(key, version=version)
|
2010-09-13 02:45:26 +08:00
|
|
|
self.validate_key(key)
|
2007-10-22 03:19:32 +08:00
|
|
|
return self._base_set('add', key, value, timeout)
|
|
|
|
|
2018-04-28 05:48:35 +08:00
|
|
|
def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):
|
|
|
|
key = self.make_key(key, version=version)
|
|
|
|
self.validate_key(key)
|
|
|
|
return self._base_set('touch', key, None, timeout)
|
|
|
|
|
2013-05-18 18:54:59 +08:00
|
|
|
def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
|
2013-09-24 00:40:19 +08:00
|
|
|
timeout = self.get_backend_timeout(timeout)
|
2010-08-05 10:13:32 +08:00
|
|
|
db = router.db_for_write(self.cache_model_class)
|
2015-05-03 04:25:57 +08:00
|
|
|
connection = connections[db]
|
2018-03-14 10:46:41 +08:00
|
|
|
quote_name = connection.ops.quote_name
|
|
|
|
table = quote_name(self._table)
|
2010-08-05 10:13:32 +08:00
|
|
|
|
2015-05-03 04:25:57 +08:00
|
|
|
with connection.cursor() as cursor:
|
2014-01-09 23:05:15 +08:00
|
|
|
cursor.execute("SELECT COUNT(*) FROM %s" % table)
|
|
|
|
num = cursor.fetchone()[0]
|
|
|
|
now = timezone.now()
|
|
|
|
now = now.replace(microsecond=0)
|
|
|
|
if timeout is None:
|
|
|
|
exp = datetime.max
|
|
|
|
elif settings.USE_TZ:
|
|
|
|
exp = datetime.utcfromtimestamp(timeout)
|
|
|
|
else:
|
|
|
|
exp = datetime.fromtimestamp(timeout)
|
|
|
|
exp = exp.replace(microsecond=0)
|
|
|
|
if num > self._max_entries:
|
|
|
|
self._cull(db, cursor, now)
|
|
|
|
pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
|
|
|
|
# The DB column is expecting a string, so make sure the value is a
|
|
|
|
# string, not bytes. Refs #19274.
|
2016-12-01 18:38:01 +08:00
|
|
|
b64encoded = base64.b64encode(pickled).decode('latin1')
|
2014-01-09 23:05:15 +08:00
|
|
|
try:
|
|
|
|
# Note: typecasting for datetimes is needed by some 3rd party
|
|
|
|
# database backends. All core backends work without typecasting,
|
|
|
|
# so be careful about changes here - test suite will NOT pick
|
|
|
|
# regressions.
|
|
|
|
with transaction.atomic(using=db):
|
2018-03-14 10:46:41 +08:00
|
|
|
cursor.execute(
|
|
|
|
'SELECT %s, %s FROM %s WHERE %s = %%s' % (
|
|
|
|
quote_name('cache_key'),
|
|
|
|
quote_name('expires'),
|
|
|
|
table,
|
|
|
|
quote_name('cache_key'),
|
|
|
|
),
|
|
|
|
[key]
|
|
|
|
)
|
2014-01-09 23:05:15 +08:00
|
|
|
result = cursor.fetchone()
|
2015-05-03 04:25:57 +08:00
|
|
|
|
2014-01-09 23:05:15 +08:00
|
|
|
if result:
|
|
|
|
current_expires = result[1]
|
2015-05-03 04:25:57 +08:00
|
|
|
expression = models.Expression(output_field=models.DateTimeField())
|
|
|
|
for converter in (connection.ops.get_db_converters(expression) +
|
|
|
|
expression.get_db_converters(connection)):
|
2017-07-07 01:18:05 +08:00
|
|
|
if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning
|
|
|
|
current_expires = converter(current_expires, expression, connection, {})
|
|
|
|
else:
|
|
|
|
current_expires = converter(current_expires, expression, connection)
|
2015-05-03 04:25:57 +08:00
|
|
|
|
|
|
|
exp = connection.ops.adapt_datetimefield_value(exp)
|
2018-04-28 05:48:35 +08:00
|
|
|
if result and mode == 'touch':
|
|
|
|
cursor.execute(
|
|
|
|
'UPDATE %s SET %s = %%s WHERE %s = %%s' % (
|
|
|
|
table,
|
|
|
|
quote_name('expires'),
|
|
|
|
quote_name('cache_key')
|
|
|
|
),
|
|
|
|
[exp, key]
|
|
|
|
)
|
|
|
|
elif result and (mode == 'set' or (mode == 'add' and current_expires < now)):
|
2018-03-14 10:46:41 +08:00
|
|
|
cursor.execute(
|
|
|
|
'UPDATE %s SET %s = %%s, %s = %%s WHERE %s = %%s' % (
|
|
|
|
table,
|
|
|
|
quote_name('value'),
|
|
|
|
quote_name('expires'),
|
|
|
|
quote_name('cache_key'),
|
|
|
|
),
|
|
|
|
[b64encoded, exp, key]
|
|
|
|
)
|
2018-04-28 05:48:35 +08:00
|
|
|
elif mode != 'touch':
|
2018-03-14 10:46:41 +08:00
|
|
|
cursor.execute(
|
|
|
|
'INSERT INTO %s (%s, %s, %s) VALUES (%%s, %%s, %%s)' % (
|
|
|
|
table,
|
|
|
|
quote_name('cache_key'),
|
|
|
|
quote_name('value'),
|
|
|
|
quote_name('expires'),
|
|
|
|
),
|
|
|
|
[key, b64encoded, exp]
|
|
|
|
)
|
2018-04-28 05:48:35 +08:00
|
|
|
else:
|
|
|
|
return False # touch failed.
|
2014-01-09 23:05:15 +08:00
|
|
|
except DatabaseError:
|
|
|
|
# To be threadsafe, updates/inserts are allowed to fail silently
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
2006-02-24 14:07:01 +08:00
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
def delete(self, key, version=None):
|
|
|
|
key = self.make_key(key, version=version)
|
2010-09-13 02:45:26 +08:00
|
|
|
self.validate_key(key)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2010-08-05 10:13:32 +08:00
|
|
|
db = router.db_for_write(self.cache_model_class)
|
2015-05-03 04:25:57 +08:00
|
|
|
connection = connections[db]
|
|
|
|
table = connection.ops.quote_name(self._table)
|
2010-08-05 10:13:32 +08:00
|
|
|
|
2015-05-03 04:25:57 +08:00
|
|
|
with connection.cursor() as cursor:
|
2014-01-09 23:05:15 +08:00
|
|
|
cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key])
|
2006-02-24 14:07:01 +08:00
|
|
|
|
2010-11-19 23:39:35 +08:00
|
|
|
def has_key(self, key, version=None):
|
|
|
|
key = self.make_key(key, version=version)
|
2010-09-13 02:45:26 +08:00
|
|
|
self.validate_key(key)
|
2010-11-19 23:39:35 +08:00
|
|
|
|
2010-08-05 10:13:32 +08:00
|
|
|
db = router.db_for_read(self.cache_model_class)
|
2015-05-03 04:25:57 +08:00
|
|
|
connection = connections[db]
|
2018-03-14 10:46:41 +08:00
|
|
|
quote_name = connection.ops.quote_name
|
2010-08-05 10:13:32 +08:00
|
|
|
|
2011-11-20 18:17:12 +08:00
|
|
|
if settings.USE_TZ:
|
|
|
|
now = datetime.utcnow()
|
|
|
|
else:
|
|
|
|
now = datetime.now()
|
|
|
|
now = now.replace(microsecond=0)
|
2014-01-09 23:05:15 +08:00
|
|
|
|
2015-05-03 04:25:57 +08:00
|
|
|
with connection.cursor() as cursor:
|
2018-03-14 10:46:41 +08:00
|
|
|
cursor.execute(
|
|
|
|
'SELECT %s FROM %s WHERE %s = %%s and expires > %%s' % (
|
|
|
|
quote_name('cache_key'),
|
|
|
|
quote_name(self._table),
|
|
|
|
quote_name('cache_key'),
|
|
|
|
),
|
|
|
|
[key, connection.ops.adapt_datetimefield_value(now)]
|
|
|
|
)
|
2014-01-09 23:05:15 +08:00
|
|
|
return cursor.fetchone() is not None
|
2006-02-24 14:07:01 +08:00
|
|
|
|
2010-08-05 10:13:32 +08:00
|
|
|
def _cull(self, db, cursor, now):
|
2006-02-24 14:07:01 +08:00
|
|
|
if self._cull_frequency == 0:
|
2010-01-27 16:21:35 +08:00
|
|
|
self.clear()
|
2006-02-24 14:07:01 +08:00
|
|
|
else:
|
2015-05-03 04:25:57 +08:00
|
|
|
connection = connections[db]
|
|
|
|
table = connection.ops.quote_name(self._table)
|
2010-08-05 10:13:32 +08:00
|
|
|
cursor.execute("DELETE FROM %s WHERE expires < %%s" % table,
|
2015-05-03 04:25:57 +08:00
|
|
|
[connection.ops.adapt_datetimefield_value(now)])
|
2010-08-05 10:13:32 +08:00
|
|
|
cursor.execute("SELECT COUNT(*) FROM %s" % table)
|
2006-02-24 14:07:01 +08:00
|
|
|
num = cursor.fetchone()[0]
|
|
|
|
if num > self._max_entries:
|
2012-08-18 17:15:05 +08:00
|
|
|
cull_num = num // self._cull_frequency
|
2012-07-05 22:20:48 +08:00
|
|
|
cursor.execute(
|
2015-05-03 04:25:57 +08:00
|
|
|
connection.ops.cache_key_culling_sql() % table,
|
2012-07-05 22:20:48 +08:00
|
|
|
[cull_num])
|
2011-11-20 18:17:12 +08:00
|
|
|
cursor.execute("DELETE FROM %s "
|
|
|
|
"WHERE cache_key < %%s" % table,
|
|
|
|
[cursor.fetchone()[0]])
|
2010-01-27 16:21:35 +08:00
|
|
|
|
|
|
|
def clear(self):
|
2010-08-05 10:13:32 +08:00
|
|
|
db = router.db_for_write(self.cache_model_class)
|
2015-05-03 04:25:57 +08:00
|
|
|
connection = connections[db]
|
|
|
|
table = connection.ops.quote_name(self._table)
|
|
|
|
with connection.cursor() as cursor:
|
2014-01-09 23:05:15 +08:00
|
|
|
cursor.execute('DELETE FROM %s' % table)
|