| 1 |
from contextlib import contextmanager |
| 2 |
from typing import Any, Optional, Tuple, Union |
| 3 |
|
| 4 |
from django.apps import apps |
| 5 |
from django.conf import settings |
| 6 |
from django.db import connections |
| 7 |
|
| 8 |
from .cache import cachalot_caches |
| 9 |
from .settings import cachalot_settings |
| 10 |
from .signals import post_invalidation |
| 11 |
from .transaction import AtomicCache |
| 12 |
from .utils import _invalidate_tables |
| 13 |
|
| 14 |
|
| 15 |
try: |
| 16 |
from asgiref.local import Local |
| 17 |
LOCAL_STORAGE = Local() |
| 18 |
except ImportError: |
| 19 |
import threading |
| 20 |
LOCAL_STORAGE = threading.local() |
| 21 |
|
| 22 |
|
| 23 |
__all__ = ('invalidate', 'get_last_invalidation', 'cachalot_disabled') |
| 24 |
|
| 25 |
|
| 26 |
def _cache_db_tables_iterator(tables, cache_alias, db_alias): |
| 27 |
no_tables = not tables |
| 28 |
cache_aliases = settings.CACHES if cache_alias is None else (cache_alias,) |
| 29 |
db_aliases = settings.DATABASES if db_alias is None else (db_alias,) |
| 30 |
for db_alias in db_aliases: |
| 31 |
if no_tables: |
| 32 |
tables = connections[db_alias].introspection.table_names() |
| 33 |
if tables: |
| 34 |
for cache_alias in cache_aliases: |
| 35 |
yield cache_alias, db_alias, tables |
| 36 |
|
| 37 |
|
| 38 |
def _get_tables(tables_or_models): |
| 39 |
for table_or_model in tables_or_models: |
| 40 |
if isinstance(table_or_model, str) and '.' in table_or_model: |
| 41 |
try: |
| 42 |
table_or_model = apps.get_model(table_or_model) |
| 43 |
except LookupError: |
| 44 |
pass |
| 45 |
yield (table_or_model if isinstance(table_or_model, str) |
| 46 |
else table_or_model._meta.db_table) |
| 47 |
|
| 48 |
|
| 49 |
def invalidate( |
| 50 |
*tables_or_models: Tuple[Union[str, Any], ...], |
| 51 |
cache_alias: Optional[str] = None, |
| 52 |
db_alias: Optional[str] = None, |
| 53 |
) -> None: |
| 54 |
""" |
| 55 |
Clears what was cached by django-cachalot implying one or more SQL tables |
| 56 |
or models from ``tables_or_models``. |
| 57 |
If ``tables_or_models`` is not specified, all tables found in the database |
| 58 |
(including those outside Django) are invalidated. |
| 59 |
|
| 60 |
If ``cache_alias`` is specified, it only clears the SQL queries stored |
| 61 |
on this cache, otherwise queries from all caches are cleared. |
| 62 |
|
| 63 |
If ``db_alias`` is specified, it only clears the SQL queries executed |
| 64 |
on this database, otherwise queries from all databases are cleared. |
| 65 |
|
| 66 |
:arg tables_or_models: SQL tables names, models or models lookups |
| 67 |
(or a combination) |
| 68 |
:type tables_or_models: tuple of strings or models |
| 69 |
:arg cache_alias: Alias from the Django ``CACHES`` setting |
| 70 |
:arg db_alias: Alias from the Django ``DATABASES`` setting |
| 71 |
:returns: Nothing |
| 72 |
""" |
| 73 |
send_signal = False |
| 74 |
invalidated = set() |
| 75 |
for cache_alias, db_alias, tables in _cache_db_tables_iterator( |
| 76 |
list(_get_tables(tables_or_models)), cache_alias, db_alias): |
| 77 |
cache = cachalot_caches.get_cache(cache_alias, db_alias) |
| 78 |
if not isinstance(cache, AtomicCache): |
| 79 |
send_signal = True |
| 80 |
_invalidate_tables(cache, db_alias, tables) |
| 81 |
invalidated.update(tables) |
| 82 |
|
| 83 |
if send_signal: |
| 84 |
for table in invalidated: |
| 85 |
post_invalidation.send(table, db_alias=db_alias) |
| 86 |
|
| 87 |
|
| 88 |
def get_last_invalidation( |
| 89 |
*tables_or_models: Tuple[Union[str, Any], ...], |
| 90 |
cache_alias: Optional[str] = None, |
| 91 |
db_alias: Optional[str] = None, |
| 92 |
) -> float: |
| 93 |
""" |
| 94 |
Returns the timestamp of the most recent invalidation of the given |
| 95 |
``tables_or_models``. If ``tables_or_models`` is not specified, |
| 96 |
all tables found in the database (including those outside Django) are used. |
| 97 |
|
| 98 |
If ``cache_alias`` is specified, it only fetches invalidations |
| 99 |
in this cache, otherwise invalidations in all caches are fetched. |
| 100 |
|
| 101 |
If ``db_alias`` is specified, it only fetches invalidations |
| 102 |
for this database, otherwise invalidations for all databases are fetched. |
| 103 |
|
| 104 |
:arg tables_or_models: SQL tables names, models or models lookups |
| 105 |
(or a combination) |
| 106 |
:type tables_or_models: tuple of strings or models |
| 107 |
:arg cache_alias: Alias from the Django ``CACHES`` setting |
| 108 |
:arg db_alias: Alias from the Django ``DATABASES`` setting |
| 109 |
:returns: The timestamp of the most recent invalidation |
| 110 |
""" |
| 111 |
last_invalidation = 0.0 |
| 112 |
for cache_alias, db_alias, tables in _cache_db_tables_iterator( |
| 113 |
list(_get_tables(tables_or_models)), cache_alias, db_alias): |
| 114 |
get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN |
| 115 |
table_cache_keys = [get_table_cache_key(db_alias, t) for t in tables] |
| 116 |
invalidations = cachalot_caches.get_cache( |
| 117 |
cache_alias, db_alias).get_many(table_cache_keys).values() |
| 118 |
if invalidations: |
| 119 |
current_last_invalidation = max(invalidations) |
| 120 |
if current_last_invalidation > last_invalidation: |
| 121 |
last_invalidation = current_last_invalidation |
| 122 |
return last_invalidation |
| 123 |
|
| 124 |
|
| 125 |
@contextmanager |
| 126 |
def cachalot_disabled(all_queries: bool = False): |
| 127 |
""" |
| 128 |
Context manager for temporarily disabling cachalot. |
| 129 |
If you evaluate the same queryset a second time, |
| 130 |
like normally for Django querysets, this will access |
| 131 |
the variable that saved it in-memory. For example: |
| 132 |
|
| 133 |
.. code-block:: python |
| 134 |
|
| 135 |
with cachalot_disabled(): |
| 136 |
qs = Test.objects.filter(blah=blah) |
| 137 |
# Does a single query to the db |
| 138 |
list(qs) # Evaluates queryset |
| 139 |
# Because the qs was evaluated, it's |
| 140 |
# saved in memory: |
| 141 |
list(qs) # this does 0 queries. |
| 142 |
# This does 1 query to the db |
| 143 |
list(Test.objects.filter(blah=blah)) |
| 144 |
|
| 145 |
If you evaluate the queryset outside the context manager, any duplicate |
| 146 |
query will use the cached result unless an object creation happens in between |
| 147 |
the original and duplicate query. |
| 148 |
|
| 149 |
:arg all_queries: Any query, including already evaluated queries, are re-evaluated. |
| 150 |
""" |
| 151 |
was_enabled = getattr(LOCAL_STORAGE, "cachalot_enabled", cachalot_settings.CACHALOT_ENABLED) |
| 152 |
LOCAL_STORAGE.cachalot_enabled = False |
| 153 |
LOCAL_STORAGE.disable_on_all = all_queries |
| 154 |
yield |
| 155 |
LOCAL_STORAGE.cachalot_enabled = was_enabled |