Completed
Push — master ( b812f7...ce9ec0 )
by Bertrand
01:05
created

_find_subqueries()   C

Complexity

Conditions 10

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
cc 10
c 7
b 0
f 0
dl 0
loc 21
rs 5.2413

How to fix   Complexity   

Complexity

Complex classes like _find_subqueries() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# coding: utf-8
2
3
from __future__ import unicode_literals
4
import datetime
5
from decimal import Decimal
6
from hashlib import sha1
7
from time import time
8
from uuid import UUID
9
10
from django import VERSION as django_version
11
from django.db import connections
12
from django.db.models import QuerySet
13
from django.db.models.sql import Query
14
from django.db.models.sql.where import (
15
    ExtraWhere, SubqueryConstraint, WhereNode)
16
from django.utils.six import text_type, binary_type, PY2
17
18
from .settings import ITERABLES, cachalot_settings
19
from .transaction import AtomicCache
20
21
22
class UncachableQuery(Exception):
23
    pass
24
25
26
class IsRawQuery(Exception):
27
    pass
28
29
30
CACHABLE_PARAM_TYPES = {
31
    bool, int, float, Decimal, bytearray, binary_type, text_type, type(None),
32
    datetime.date, datetime.time, datetime.datetime, datetime.timedelta, UUID,
33
}
34
35
if PY2:
36
    CACHABLE_PARAM_TYPES.add(long)
37
38
UNCACHABLE_FUNCS = set()
39
if django_version[:2] >= (1, 9):
40
    from django.db.models.functions import Now
41
    from django.contrib.postgres.functions import TransactionNow
42
    UNCACHABLE_FUNCS.update((Now, TransactionNow))
43
44
try:
45
    from psycopg2 import Binary
46
    from psycopg2.extras import (
47
        NumericRange, DateRange, DateTimeRange, DateTimeTZRange, Inet, Json)
48
except ImportError:
49
    pass
50
else:
51
    CACHABLE_PARAM_TYPES.update((
52
        Binary,
53
        NumericRange, DateRange, DateTimeRange, DateTimeTZRange, Inet, Json))
54
    if django_version[:2] >= (1, 11):
55
        from django.contrib.postgres.fields.jsonb import JsonAdapter
56
        CACHABLE_PARAM_TYPES.add(JsonAdapter)
57
58
59
def check_parameter_types(params):
60
    for p in params:
61
        cl = p.__class__
62
        if cl not in CACHABLE_PARAM_TYPES:
63
            if cl in ITERABLES:
64
                check_parameter_types(p)
65
            elif cl is dict:
66
                check_parameter_types(p.items())
67
            else:
68
                raise UncachableQuery
69
70
71
def get_query_cache_key(compiler):
72
    """
73
    Generates a cache key from a SQLCompiler.
74
75
    This cache key is specific to the SQL query and its context
76
    (which database is used).  The same query in the same context
77
    (= the same database) must generate the same cache key.
78
79
    :arg compiler: A SQLCompiler that will generate the SQL query
80
    :type compiler: django.db.models.sql.compiler.SQLCompiler
81
    :return: A cache key
82
    :rtype: int
83
    """
84
    sql, params = compiler.as_sql()
85
    check_parameter_types(params)
86
    cache_key = '%s:%s:%s' % (compiler.using, sql,
87
                              [text_type(p) for p in params])
88
    return sha1(cache_key.encode('utf-8')).hexdigest()
89
90
91
def get_table_cache_key(db_alias, table):
92
    """
93
    Generates a cache key from a SQL table.
94
95
    :arg db_alias: Alias of the used database
96
    :type db_alias: str or unicode
97
    :arg table: Name of the SQL table
98
    :type table: str or unicode
99
    :return: A cache key
100
    :rtype: int
101
    """
102
    cache_key = '%s:%s' % (db_alias, table)
103
    return sha1(cache_key.encode('utf-8')).hexdigest()
104
105
106
def _get_tables_from_sql(connection, lowercased_sql):
107
    return {t for t in connection.introspection.django_table_names()
108
            if t in lowercased_sql}
109
110
111
def _find_subqueries(children):
112
    for child in children:
113
        child_class = child.__class__
114
        if child_class is WhereNode:
115
            for grand_child in _find_subqueries(child.children):
116
                yield grand_child
117
        elif child_class is SubqueryConstraint:
118
            query_object = child.query_object
119
            yield (query_object if query_object.__class__ is Query
120
                   else query_object.query)
121
        elif child_class is ExtraWhere:
122
            raise IsRawQuery
123
        else:
124
            rhs = getattr(child, 'rhs', None)
125
            rhs_class = rhs.__class__
126
            if rhs_class is Query:
127
                yield rhs
128
            elif rhs_class is QuerySet:
129
                yield rhs.query
130
            elif rhs_class in UNCACHABLE_FUNCS:
131
                raise UncachableQuery
132
133
134
def is_cachable(table):
135
    whitelist = cachalot_settings.CACHALOT_ONLY_CACHABLE_TABLES
136
    if whitelist and table not in whitelist:
137
        return False
138
    return table not in cachalot_settings.CACHALOT_UNCACHABLE_TABLES
139
140
141
def are_all_cachable(tables):
142
    whitelist = cachalot_settings.CACHALOT_ONLY_CACHABLE_TABLES
143
    if whitelist and not tables.issubset(whitelist):
144
        return False
145
    return tables.isdisjoint(cachalot_settings.CACHALOT_UNCACHABLE_TABLES)
146
147
148
def filter_cachable(tables):
149
    whitelist = cachalot_settings.CACHALOT_ONLY_CACHABLE_TABLES
150
    tables = tables.difference(cachalot_settings.CACHALOT_UNCACHABLE_TABLES)
151
    if whitelist:
152
        return tables.intersection(whitelist)
153
    return tables
154
155
156
def _get_tables(db_alias, query):
157
    if query.select_for_update or (
158
            '?' in query.order_by
159
            and not cachalot_settings.CACHALOT_CACHE_RANDOM):
160
        raise UncachableQuery
161
162
    try:
163
        if query.extra_select or getattr(query, 'subquery', False):
164
            raise IsRawQuery
165
        tables = set(query.table_map)
166
        tables.add(query.get_meta().db_table)
167
        for subquery in _find_subqueries(query.where.children):
168
            tables.update(_get_tables(db_alias, subquery))
169
    except IsRawQuery:
170
        sql = query.get_compiler(db_alias).as_sql()[0].lower()
171
        tables = _get_tables_from_sql(connections[db_alias], sql)
172
173
    if not are_all_cachable(tables):
174
        raise UncachableQuery
175
    return tables
176
177
178
def _get_table_cache_keys(compiler):
179
    db_alias = compiler.using
180
    get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN
181
    return [get_table_cache_key(db_alias, t)
182
            for t in _get_tables(db_alias, compiler.query)]
183
184
185
def _invalidate_tables(cache, db_alias, tables):
186
    tables = filter_cachable(set(tables))
187
    if not tables:
188
        return
189
    now = time()
190
    get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN
191
    cache.set_many(
192
        {get_table_cache_key(db_alias, t): now for t in tables},
193
        cachalot_settings.CACHALOT_TIMEOUT)
194
195
    if isinstance(cache, AtomicCache):
196
        cache.to_be_invalidated.update(tables)
197