django-cachalot/cachalot/monkey_patch.py
Andrew-Chen-Wang 602cdcee1d
Version 2.2.0 (#146)
This PR upgrades cachalot to version 2.2.0 allowing for anyone to install cachalot at any Django package above 1.11. All tests currently function now.

* Added mysql as a service to fix Travis CI

* Removed tox dependency

* Removed upper limit on Django and support 2.2-3.0 CI Test
* Cachalot will only say "officially supports" while removing upper limit to not hinder anyone's progress.
* Added Python 3.8 and Django 2.2 and 3.0 to CI tests

- Max is 200 and we'll get there quickly if we add another Python version. Utilizes #127
- Keep dependencies for six and django.utils.six

* Correctly run Travis test by updating tox.ini
* Originally using tox syntax but changed testenv to travis so that travis env and travis dependencies and stuff are used

* Tox tests should start running command

* testenv without dependencies broke travis. New spot in Tox
* testenv without dependencies broke travis
* I can't figure out where testenv is supposed to be
* Good thing there's squash

* Added missing six in test
* Also added six package to Tox for Django 3.0 coverage.
* The missing six package caused several problems in several tests due to using an incorrect DB

* Resolves #138
* Need to add the panels here in order to satisfy tests

* Adds CachalotPanel to Python 2 backwards compatibility
* Forgot super class took those like save()

* Added databases to certain test cases
* APITestCase, DebugToolbarTestCase, SignalsTestCase required a database set
* Fixes errors like these: https://travis-ci.org/noripyt/django-cachalot/jobs/648691385#L4892

* Dropped OFFICIAL support for Python 3.4 + MySQL
* MySQL and its client on 3.4 is f--king up a lot of the testing and I can't bear with it. We can revisit it later, but, honestly, who uses Python 3.4... and if an organization is, then they will either have no problem with Postgres and SQLite or know that MySQL doesn't work.

* Drop Py3.4 from running. Fixed databases
* Now goes with setting's databases rather than hardcoded since some tests don't have other databases.

* Fix ReadTestCase

Django 2.2+ changed self.queryset at line 1000 with self.query=queryset.query

* Django Dependency Removed from utils.py

* Last commit used Django version. This one used try except

* Fixed assertNumQuery; added allow_failures for 3.4
* Primary: More information in test_utils.py with method is_django_21_below_and_is_sqlite
* The problem with the entire build lie in the self.is_sqlite for the tests. SQLite will make 2 queries when creating or destroying or updating instead of 1.
* In summary, if SQLite is the DB and Django

* Changed build matrix to allow failures for 3.4 instead of taking it out completely so that we can get it to work soon.

* Remove -> From function return
* I love backwards compatibility

* SQLite2 in multi_db.py returned incorrect bool

* Django 2.1 and SQLite checker doesn't work for some tests
* Some tests DO HAVE the BEGIN query that is returned... Not sure why. If the next test show completely different WriteTestCase problems, then we need to find alternative.
* Removed check from atomic

* Adjust Django and is_sqlite errors
* CI testing the Tox errors: https://travis-ci.org/noripyt/django-cachalot?utm_medium=notification&utm_source=github_status

* Adjust Django and is_sqlite errors (590 CI)
* CI testing the Tox errors: https://travis-ci.org/noripyt/django-cachalot?utm_medium=notification&utm_source=github_status
* Adjustment 2

* Make include matrix and Adjust Django and is_sqlite errors (594 CI)
* CI testing the Tox errors: https://travis-ci.org/noripyt/django-cachalot?utm_medium=notification&utm_source=github_status
* Adjustment 3

* Adjust Django and is_sqlite errors (596 CI)
* CI testing the Tox errors: https://travis-ci.org/noripyt/django-cachalot?utm_medium=notification&utm_source=github_status
* Adjustment 4
* Added my intro to ReadTheDocs

* Adjust Django and is_sqlite errors (598 CI)
* CI testing the Tox errors: https://travis-ci.org/noripyt/django-cachalot?utm_medium=notification&utm_source=github_status
* Adjustment 5

* Drop Python 3.4 from tests since PyLibMC not cooperating at that level.

* Bump package version up 1 minor for Django 2.2 and 3.0
2020-02-12 00:52:12 -05:00

207 lines
6.5 KiB
Python

# coding: utf-8
from __future__ import unicode_literals
from collections import Iterable
from time import time
from django.db.backends.utils import CursorWrapper
from django.db.models.query import EmptyResultSet
from django.db.models.signals import post_migrate
from django.db.models.sql.compiler import (
SQLCompiler, SQLInsertCompiler, SQLUpdateCompiler, SQLDeleteCompiler,
)
from django.db.transaction import Atomic, get_connection
try:
from django.utils.six import binary_type, wraps
except ImportError:
from six import binary_type, wraps
from .api import invalidate
from .cache import cachalot_caches
from .settings import cachalot_settings, ITERABLES
from .utils import (
_get_table_cache_keys, _get_tables_from_sql,
UncachableQuery, is_cachable, filter_cachable,
)
WRITE_COMPILERS = (SQLInsertCompiler, SQLUpdateCompiler, SQLDeleteCompiler)
def _unset_raw_connection(original):
def inner(compiler, *args, **kwargs):
compiler.connection.raw = False
try:
return original(compiler, *args, **kwargs)
finally:
compiler.connection.raw = True
return inner
def _get_result_or_execute_query(execute_query_func, cache,
cache_key, table_cache_keys):
data = cache.get_many(table_cache_keys + [cache_key])
new_table_cache_keys = set(table_cache_keys)
new_table_cache_keys.difference_update(data)
if not new_table_cache_keys:
try:
timestamp, result = data.pop(cache_key)
if timestamp >= max(data.values()):
return result
except (KeyError, TypeError, ValueError):
# In case `cache_key` is not in `data` or contains bad data,
# we simply run the query and cache again the results.
pass
result = execute_query_func()
if result.__class__ not in ITERABLES and isinstance(result, Iterable):
result = list(result)
now = time()
to_be_set = {k: now for k in new_table_cache_keys}
to_be_set[cache_key] = (now, result)
cache.set_many(to_be_set, cachalot_settings.CACHALOT_TIMEOUT)
return result
def _patch_compiler(original):
@wraps(original)
@_unset_raw_connection
def inner(compiler, *args, **kwargs):
execute_query_func = lambda: original(compiler, *args, **kwargs)
db_alias = compiler.using
if db_alias not in cachalot_settings.CACHALOT_DATABASES \
or isinstance(compiler, WRITE_COMPILERS):
return execute_query_func()
try:
cache_key = cachalot_settings.CACHALOT_QUERY_KEYGEN(compiler)
table_cache_keys = _get_table_cache_keys(compiler)
except (EmptyResultSet, UncachableQuery):
return execute_query_func()
return _get_result_or_execute_query(
execute_query_func,
cachalot_caches.get_cache(db_alias=db_alias),
cache_key, table_cache_keys)
return inner
def _patch_write_compiler(original):
@wraps(original)
@_unset_raw_connection
def inner(write_compiler, *args, **kwargs):
db_alias = write_compiler.using
table = write_compiler.query.get_meta().db_table
if is_cachable(table):
invalidate(table, db_alias=db_alias,
cache_alias=cachalot_settings.CACHALOT_CACHE)
return original(write_compiler, *args, **kwargs)
return inner
def _patch_orm():
if cachalot_settings.CACHALOT_ENABLED:
SQLCompiler.execute_sql = _patch_compiler(SQLCompiler.execute_sql)
for compiler in WRITE_COMPILERS:
compiler.execute_sql = _patch_write_compiler(compiler.execute_sql)
def _unpatch_orm():
if hasattr(SQLCompiler.execute_sql, '__wrapped__'):
SQLCompiler.execute_sql = SQLCompiler.execute_sql.__wrapped__
for compiler in WRITE_COMPILERS:
compiler.execute_sql = compiler.execute_sql.__wrapped__
def _patch_cursor():
def _patch_cursor_execute(original):
@wraps(original)
def inner(cursor, sql, *args, **kwargs):
try:
return original(cursor, sql, *args, **kwargs)
finally:
connection = cursor.db
if getattr(connection, 'raw', True):
if isinstance(sql, binary_type):
sql = sql.decode('utf-8')
sql = sql.lower()
if 'update' in sql or 'insert' in sql or 'delete' in sql \
or 'alter' in sql or 'create' in sql \
or 'drop' in sql:
tables = filter_cachable(
_get_tables_from_sql(connection, sql))
if tables:
invalidate(
*tables, db_alias=connection.alias,
cache_alias=cachalot_settings.CACHALOT_CACHE)
return inner
if cachalot_settings.CACHALOT_INVALIDATE_RAW:
CursorWrapper.execute = _patch_cursor_execute(CursorWrapper.execute)
CursorWrapper.executemany = \
_patch_cursor_execute(CursorWrapper.executemany)
def _unpatch_cursor():
if hasattr(CursorWrapper.execute, '__wrapped__'):
CursorWrapper.execute = CursorWrapper.execute.__wrapped__
CursorWrapper.executemany = CursorWrapper.executemany.__wrapped__
def _patch_atomic():
def patch_enter(original):
@wraps(original)
def inner(self):
cachalot_caches.enter_atomic(self.using)
original(self)
return inner
def patch_exit(original):
@wraps(original)
def inner(self, exc_type, exc_value, traceback):
needs_rollback = get_connection(self.using).needs_rollback
try:
original(self, exc_type, exc_value, traceback)
finally:
cachalot_caches.exit_atomic(
self.using, exc_type is None and not needs_rollback)
return inner
Atomic.__enter__ = patch_enter(Atomic.__enter__)
Atomic.__exit__ = patch_exit(Atomic.__exit__)
def _unpatch_atomic():
Atomic.__enter__ = Atomic.__enter__.__wrapped__
Atomic.__exit__ = Atomic.__exit__.__wrapped__
def _invalidate_on_migration(sender, **kwargs):
invalidate(*sender.get_models(), db_alias=kwargs['using'],
cache_alias=cachalot_settings.CACHALOT_CACHE)
def patch():
post_migrate.connect(_invalidate_on_migration)
_patch_cursor()
_patch_atomic()
_patch_orm()
def unpatch():
post_migrate.disconnect(_invalidate_on_migration)
_unpatch_cursor()
_unpatch_atomic()
_unpatch_orm()