| 1 |
import re |
| 2 |
import types |
| 3 |
from collections.abc import Iterable |
| 4 |
from functools import wraps |
| 5 |
from time import time |
| 6 |
|
| 7 |
from django.core.exceptions import EmptyResultSet |
| 8 |
from django.db.backends.utils import CursorWrapper |
| 9 |
from django.db.models.signals import post_migrate |
| 10 |
from django.db.models.sql.compiler import ( |
| 11 |
SQLCompiler, SQLInsertCompiler, SQLUpdateCompiler, SQLDeleteCompiler, |
| 12 |
) |
| 13 |
from django.db.transaction import Atomic, get_connection |
| 14 |
|
| 15 |
from .api import invalidate, LOCAL_STORAGE |
| 16 |
from .cache import cachalot_caches |
| 17 |
from .settings import cachalot_settings, ITERABLES |
| 18 |
from .utils import ( |
| 19 |
_get_table_cache_keys, _get_tables_from_sql, |
| 20 |
UncachableQuery, is_cachable, filter_cachable, |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
WRITE_COMPILERS = (SQLInsertCompiler, SQLUpdateCompiler, SQLDeleteCompiler) |
| 25 |
|
| 26 |
SQL_DATA_CHANGE_RE = re.compile( |
| 27 |
'|'.join([ |
| 28 |
fr'(\W|\A){re.escape(keyword)}(\W|\Z)' |
| 29 |
for keyword in ['update', 'insert', 'delete', 'alter', 'create', 'drop'] |
| 30 |
]), |
| 31 |
flags=re.IGNORECASE, |
| 32 |
) |
| 33 |
|
| 34 |
def _unset_raw_connection(original): |
| 35 |
def inner(compiler, *args, **kwargs): |
| 36 |
compiler.connection.raw = False |
| 37 |
try: |
| 38 |
return original(compiler, *args, **kwargs) |
| 39 |
finally: |
| 40 |
compiler.connection.raw = True |
| 41 |
return inner |
| 42 |
|
| 43 |
|
| 44 |
def _get_result_or_execute_query(execute_query_func, cache, |
| 45 |
cache_key, table_cache_keys): |
| 46 |
try: |
| 47 |
data = cache.get_many(table_cache_keys + [cache_key]) |
| 48 |
except (KeyError, ModuleNotFoundError): |
| 49 |
data = None |
| 50 |
|
| 51 |
new_table_cache_keys = set(table_cache_keys) |
| 52 |
if data: |
| 53 |
new_table_cache_keys.difference_update(data) |
| 54 |
|
| 55 |
if not new_table_cache_keys: |
| 56 |
try: |
| 57 |
timestamp, result = data.pop(cache_key) |
| 58 |
if timestamp >= max(data.values()): |
| 59 |
return result |
| 60 |
except (KeyError, TypeError, ValueError): |
| 61 |
# In case `cache_key` is not in `data` or contains bad data, |
| 62 |
# we simply run the query and cache again the results. |
| 63 |
pass |
| 64 |
|
| 65 |
result = execute_query_func() |
| 66 |
|
| 67 |
if result.__class__ == types.GeneratorType and not cachalot_settings.CACHALOT_CACHE_ITERATORS: |
| 68 |
return result |
| 69 |
|
| 70 |
if result.__class__ not in ITERABLES and isinstance(result, Iterable): |
| 71 |
result = list(result) |
| 72 |
|
| 73 |
now = time() |
| 74 |
to_be_set = {k: now for k in new_table_cache_keys} |
| 75 |
to_be_set[cache_key] = (now, result) |
| 76 |
cache.set_many(to_be_set, cachalot_settings.CACHALOT_TIMEOUT) |
| 77 |
|
| 78 |
return result |
| 79 |
|
| 80 |
|
| 81 |
def _patch_compiler(original): |
| 82 |
@wraps(original) |
| 83 |
@_unset_raw_connection |
| 84 |
def inner(compiler, *args, **kwargs): |
| 85 |
execute_query_func = lambda: original(compiler, *args, **kwargs) |
| 86 |
# Checks if utils/cachalot_disabled |
| 87 |
if not getattr(LOCAL_STORAGE, "cachalot_enabled", True): |
| 88 |
return execute_query_func() |
| 89 |
|
| 90 |
db_alias = compiler.using |
| 91 |
if db_alias not in cachalot_settings.CACHALOT_DATABASES \ |
| 92 |
or isinstance(compiler, WRITE_COMPILERS): |
| 93 |
return execute_query_func() |
| 94 |
|
| 95 |
try: |
| 96 |
cache_key = cachalot_settings.CACHALOT_QUERY_KEYGEN(compiler) |
| 97 |
table_cache_keys = _get_table_cache_keys(compiler) |
| 98 |
except (EmptyResultSet, UncachableQuery): |
| 99 |
return execute_query_func() |
| 100 |
|
| 101 |
return _get_result_or_execute_query( |
| 102 |
execute_query_func, |
| 103 |
cachalot_caches.get_cache(db_alias=db_alias), |
| 104 |
cache_key, table_cache_keys) |
| 105 |
|
| 106 |
return inner |
| 107 |
|
| 108 |
|
| 109 |
def _patch_write_compiler(original): |
| 110 |
@wraps(original) |
| 111 |
@_unset_raw_connection |
| 112 |
def inner(write_compiler, *args, **kwargs): |
| 113 |
db_alias = write_compiler.using |
| 114 |
table = write_compiler.query.get_meta().db_table |
| 115 |
if is_cachable(table): |
| 116 |
invalidate(table, db_alias=db_alias, |
| 117 |
cache_alias=cachalot_settings.CACHALOT_CACHE) |
| 118 |
return original(write_compiler, *args, **kwargs) |
| 119 |
|
| 120 |
return inner |
| 121 |
|
| 122 |
|
| 123 |
def _patch_orm(): |
| 124 |
if cachalot_settings.CACHALOT_ENABLED: |
| 125 |
SQLCompiler.execute_sql = _patch_compiler(SQLCompiler.execute_sql) |
| 126 |
for compiler in WRITE_COMPILERS: |
| 127 |
compiler.execute_sql = _patch_write_compiler(compiler.execute_sql) |
| 128 |
|
| 129 |
|
| 130 |
def _unpatch_orm(): |
| 131 |
if hasattr(SQLCompiler.execute_sql, '__wrapped__'): |
| 132 |
SQLCompiler.execute_sql = SQLCompiler.execute_sql.__wrapped__ |
| 133 |
for compiler in WRITE_COMPILERS: |
| 134 |
compiler.execute_sql = compiler.execute_sql.__wrapped__ |
| 135 |
|
| 136 |
|
| 137 |
def _patch_cursor(): |
| 138 |
def _patch_cursor_execute(original): |
| 139 |
@wraps(original) |
| 140 |
def inner(cursor, sql, *args, **kwargs): |
| 141 |
try: |
| 142 |
return original(cursor, sql, *args, **kwargs) |
| 143 |
finally: |
| 144 |
connection = cursor.db |
| 145 |
if getattr(connection, 'raw', True): |
| 146 |
if isinstance(sql, bytes): |
| 147 |
sql = sql.decode('utf-8') |
| 148 |
sql = sql.lower() |
| 149 |
if SQL_DATA_CHANGE_RE.search(sql): |
| 150 |
tables = filter_cachable( |
| 151 |
_get_tables_from_sql(connection, sql)) |
| 152 |
if tables: |
| 153 |
invalidate( |
| 154 |
*tables, db_alias=connection.alias, |
| 155 |
cache_alias=cachalot_settings.CACHALOT_CACHE) |
| 156 |
|
| 157 |
return inner |
| 158 |
|
| 159 |
if cachalot_settings.CACHALOT_INVALIDATE_RAW: |
| 160 |
CursorWrapper.execute = _patch_cursor_execute(CursorWrapper.execute) |
| 161 |
CursorWrapper.executemany = _patch_cursor_execute(CursorWrapper.executemany) |
| 162 |
|
| 163 |
|
| 164 |
def _unpatch_cursor(): |
| 165 |
if hasattr(CursorWrapper.execute, '__wrapped__'): |
| 166 |
CursorWrapper.execute = CursorWrapper.execute.__wrapped__ |
| 167 |
CursorWrapper.executemany = CursorWrapper.executemany.__wrapped__ |
| 168 |
|
| 169 |
|
| 170 |
def _patch_atomic(): |
| 171 |
def patch_enter(original): |
| 172 |
@wraps(original) |
| 173 |
def inner(self): |
| 174 |
cachalot_caches.enter_atomic(self.using) |
| 175 |
original(self) |
| 176 |
|
| 177 |
return inner |
| 178 |
|
| 179 |
def patch_exit(original): |
| 180 |
@wraps(original) |
| 181 |
def inner(self, exc_type, exc_value, traceback): |
| 182 |
needs_rollback = get_connection(self.using).needs_rollback |
| 183 |
try: |
| 184 |
original(self, exc_type, exc_value, traceback) |
| 185 |
finally: |
| 186 |
cachalot_caches.exit_atomic( |
| 187 |
self.using, exc_type is None and not needs_rollback) |
| 188 |
|
| 189 |
return inner |
| 190 |
|
| 191 |
Atomic.__enter__ = patch_enter(Atomic.__enter__) |
| 192 |
Atomic.__exit__ = patch_exit(Atomic.__exit__) |
| 193 |
|
| 194 |
|
| 195 |
def _unpatch_atomic(): |
| 196 |
Atomic.__enter__ = Atomic.__enter__.__wrapped__ |
| 197 |
Atomic.__exit__ = Atomic.__exit__.__wrapped__ |
| 198 |
|
| 199 |
|
| 200 |
def _invalidate_on_migration(sender, **kwargs): |
| 201 |
invalidate(*sender.get_models(), db_alias=kwargs['using'], |
| 202 |
cache_alias=cachalot_settings.CACHALOT_CACHE) |
| 203 |
|
| 204 |
|
| 205 |
def patch(): |
| 206 |
post_migrate.connect(_invalidate_on_migration) |
| 207 |
|
| 208 |
_patch_cursor() |
| 209 |
_patch_atomic() |
| 210 |
_patch_orm() |
| 211 |
|
| 212 |
|
| 213 |
def unpatch(): |
| 214 |
post_migrate.disconnect(_invalidate_on_migration) |
| 215 |
|
| 216 |
_unpatch_cursor() |
| 217 |
_unpatch_atomic() |
| 218 |
_unpatch_orm() |