diff --git a/cachalot/monkey_patch.py b/cachalot/monkey_patch.py index 481ff9e..38e2ccf 100644 --- a/cachalot/monkey_patch.py +++ b/cachalot/monkey_patch.py @@ -1,9 +1,11 @@ # coding: utf-8 from __future__ import unicode_literals -from collections import Iterable +from collections import defaultdict, Iterable import re +from django.conf import settings +# TODO: Replace with caches[CACHALOT_CACHE] when we drop Django 1.6 support. from django.core.cache import get_cache as get_django_cache from django.db import connection from django.db.models.query import EmptyResultSet @@ -12,7 +14,8 @@ from django.db.models.sql.compiler import ( SQLInsertCompiler, SQLUpdateCompiler, SQLDeleteCompiler) from django.db.models.sql.where import ExtraWhere from django.db.transaction import Atomic -from .settings import CACHALOT_CACHE + +from .settings import cachalot_settings COMPILERS = (SQLCompiler, @@ -35,8 +38,12 @@ def _get_tables(query): return tables +def _get_table_cache_key(table): + return '%s_queries' % table + + def _get_tables_cache_keys(query): - return ['%s_queries' % t for t in _get_tables(query)] + return map(_get_table_cache_key, _get_tables(query)) def _update_tables_queries(cache, query, cache_key): @@ -49,13 +56,30 @@ def _update_tables_queries(cache, query, cache_key): cache.set_many(tables_queries) -def _invalidate_tables(cache, query): - tables_cache_keys = _get_tables_cache_keys(query) +def _invalidate_tables_cache_keys(cache, tables_cache_keys): tables_queries = cache.get_many(tables_cache_keys) queries = [q for k in tables_cache_keys for q in tables_queries.get(k, [])] cache.delete_many(queries + tables_cache_keys) +def _invalidate_tables(cache, query): + tables_cache_keys = _get_tables_cache_keys(query) + _invalidate_tables_cache_keys(cache, tables_cache_keys) + + +def clear_cache(cache=None): + if cache is None: + cache = get_cache() + tables = connection.introspection.table_names() + tables_cache_keys = map(_get_table_cache_key, tables) + _invalidate_tables_cache_keys(cache, tables_cache_keys) + + +def clear_all_caches(): + for cache in settings.CACHES: + clear_cache(get_django_cache(cache)) + + COLUMN_RE = re.compile(r'^"(?P