|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from __future__ import absolute_import, print_function, unicode_literals |
| 3 | + |
| 4 | +from sqlalchemy.orm.interfaces import MapperOption |
| 5 | + |
| 6 | +from django.core.exceptions import ImproperlyConfigured |
| 7 | + |
| 8 | + |
| 9 | +def _key_from_query(query): |
| 10 | + """ |
| 11 | + Given a Query, create a cache key. |
| 12 | +
|
| 13 | + There are many approaches to this; here we use the simplest, which is to create an md5 hash of the text of the SQL |
| 14 | + statement, combined with stringified versions of all the bound parameters within it. There's a bit of a |
| 15 | + performance hit with compiling out "query.statement" here; other approaches include setting up an explicit cache |
| 16 | + key with a particular Query, then combining that with the bound parameter values. |
| 17 | + """ |
| 18 | + |
| 19 | + stmt = query.with_labels().statement |
| 20 | + compiled = stmt.compile() |
| 21 | + params = compiled.params |
| 22 | + return " ".join([str(compiled)] + [str(params[k]) for k in sorted(params)]) |
| 23 | + |
| 24 | + |
| 25 | +class FromCache(MapperOption): |
| 26 | + """Specifies that a Query should load results from a cache.""" |
| 27 | + |
| 28 | + propagate_to_loaders = False |
| 29 | + |
| 30 | + def __init__(self, region, expiration_time=None, key_maker=_key_from_query): |
| 31 | + """ |
| 32 | + Provides caching mechanism for a query |
| 33 | + -------------------------------------- |
| 34 | +
|
| 35 | + region: any |
| 36 | + The cache region. Can be a dogpile.cache region object |
| 37 | +
|
| 38 | + expiration_time: int or datetime.timedelta |
| 39 | + The expiration time that will be passed to region. |
| 40 | +
|
| 41 | + keymaker: callable |
| 42 | + A callable that will take the query and generate a cache key out of it. |
| 43 | +
|
| 44 | + Note that this approach does *not* detach the loaded objects from the current session. If the cache backend is |
| 45 | + an in-process cache (like "memory") and lives beyond the scope of the current session's transaction, those |
| 46 | + objects may be expired. The method here can be modified to first expunge() each loaded item from the current |
| 47 | + session before returning the list of items, so that the items in the cache are not the same ones in the |
| 48 | + current Session. |
| 49 | + """ |
| 50 | + if region is None: |
| 51 | + raise ImproperlyConfigured("FromCache requires a cache region") |
| 52 | + self.expiration_time = expiration_time |
| 53 | + self.key_maker = key_maker |
| 54 | + self.region = region |
| 55 | + |
| 56 | + def process_query(self, query): |
| 57 | + """Process a Query during normal loading operation.""" |
| 58 | + query.caching_option = self |
| 59 | + |
| 60 | + def get(self, query, merge=True, createfunc=None): |
| 61 | + """ |
| 62 | + Return the value from the cache for this query. |
| 63 | + """ |
| 64 | + createfunc = query.__iter__ |
| 65 | + cache_key = self.key_maker(query) |
| 66 | + cached_value = self.region.get_or_create( |
| 67 | + cache_key, lambda: list(createfunc()), expiration_time=self.expiration_time |
| 68 | + ) |
| 69 | + if merge: |
| 70 | + cached_value = query.merge_result(cached_value, load=False) |
| 71 | + return cached_value |
| 72 | + |
| 73 | + def invalidate(self, query): |
| 74 | + cache_key = self.key_maker(query) |
| 75 | + self.region.delete(cache_key) |
0 commit comments