Debian Codegraph @

cachalot/utils.py

raw
1 import datetime
2 from decimal import Decimal
3 from hashlib import sha1
4 from time import time
5 from typing import TYPE_CHECKING
6 from uuid import UUID
7
8 from django.contrib.postgres.functions import TransactionNow
9 from django.db.models import Exists, QuerySet, Subquery
10 from django.db.models.enums import Choices
11 from django.db.models.expressions import RawSQL
12 from django.db.models.functions import Now
13 from django.db.models.sql import Query, AggregateQuery
14 from django.db.models.sql.where import ExtraWhere, WhereNode, NothingNode
15
16 from .settings import ITERABLES, cachalot_settings
17 from .transaction import AtomicCache
18
19
20 if TYPE_CHECKING:
21 from django.db.models.expressions import BaseExpression
22
23
24 class UncachableQuery(Exception):
25 pass
26
27
28 class IsRawQuery(Exception):
29 pass
30
31
32 CACHABLE_PARAM_TYPES = {
33 bool, int, float, Decimal, bytearray, bytes, str, type(None),
34 datetime.date, datetime.time, datetime.datetime, datetime.timedelta, UUID,
35 }
36 UNCACHABLE_FUNCS = {Now, TransactionNow}
37
38
39 try:
40 from psycopg.dbapi20 import Binary
41
42 from django.db.backends.postgresql.psycopg_any import (
43 NumericRange, DateRange, DateTimeRange, DateTimeTZRange, Inet,
44 )
45
46 from psycopg.types.numeric import (
47 Int2, Int4, Int8, Float4, Float8,
48 )
49
50 from ipaddress import (
51 IPv4Address,
52 IPv6Address,
53 )
54
55 from psycopg.types.json import (
56 Json, Jsonb,
57 )
58
59 CACHABLE_PARAM_TYPES.update((
60 NumericRange, DateRange, DateTimeRange, DateTimeTZRange, Inet, Json, Jsonb,
61 Int2, Int4, Int8, Float4, Float8, IPv4Address, IPv6Address,
62 Binary,
63 ))
64 except ImportError:
65 try:
66 from psycopg2 import Binary
67 from psycopg2.extras import (
68 NumericRange, DateRange, DateTimeRange, DateTimeTZRange, Inet, Json)
69 CACHABLE_PARAM_TYPES.update((
70 Binary, NumericRange, DateRange, DateTimeRange, DateTimeTZRange, Inet,
71 Json,))
72 except ImportError:
73 pass
74
75
76 def check_parameter_types(params):
77 for p in params:
78 cl = p.__class__
79 if cl not in CACHABLE_PARAM_TYPES:
80 if cl in ITERABLES:
81 check_parameter_types(p)
82 elif cl is dict:
83 check_parameter_types(p.items())
84 elif issubclass(cl, Choices):
85 # Handle the case where a parameter from a Choices field is passed.
86 # Django Choices use enum.unique() so the values are guaranteed to be unique.
87 # Dereference the true "value" and verify that it is cachable.
88 check_parameter_types([p.value])
89 else:
90 raise UncachableQuery
91
92
93 def get_query_cache_key(compiler):
94 """
95 Generates a cache key from a SQLCompiler.
96
97 This cache key is specific to the SQL query and its context
98 (which database is used). The same query in the same context
99 (= the same database) must generate the same cache key.
100
101 :arg compiler: A SQLCompiler that will generate the SQL query
102 :type compiler: django.db.models.sql.compiler.SQLCompiler
103 :return: A cache key
104 :rtype: int
105 """
106 sql, params = compiler.as_sql()
107 check_parameter_types(params)
108 cache_key = '%s:%s:%s' % (compiler.using, sql,
109 [str(p) for p in params])
110 # Set attribute on compiler for later access
111 # to the generated SQL. This prevents another as_sql() call!
112 compiler.__cachalot_generated_sql = sql.lower()
113
114 return sha1(cache_key.encode('utf-8')).hexdigest()
115
116
117 def get_table_cache_key(db_alias, table):
118 """
119 Generates a cache key from a SQL table.
120
121 :arg db_alias: Alias of the used database
122 :type db_alias: str or unicode
123 :arg table: Name of the SQL table
124 :type table: str or unicode
125 :return: A cache key
126 :rtype: int
127 """
128 cache_key = '%s:%s' % (db_alias, table)
129 return sha1(cache_key.encode('utf-8')).hexdigest()
130
131
132 def _get_tables_from_sql(connection, lowercased_sql, enable_quote: bool = False):
133 """Returns names of involved tables after analyzing the final SQL query."""
134 return {table for table in (connection.introspection.django_table_names()
135 + cachalot_settings.CACHALOT_ADDITIONAL_TABLES)
136 if _quote_table_name(table, connection, enable_quote) in lowercased_sql}
137
138
139 def _quote_table_name(table_name, connection, enable_quote: bool):
140 """
141 Returns quoted table name.
142
143 Put database-specific quotation marks around the table name
144 to preven that tables with substrings of the table are considered.
145 E.g. cachalot_testparent must not return cachalot_test.
146 """
147 return f'{connection.ops.quote_name(table_name)}' \
148 if enable_quote else table_name
149
150
151 def _find_rhs_lhs_subquery(side):
152 h_class = side.__class__
153 if h_class is Query:
154 return side
155 elif h_class is QuerySet:
156 return side.query
157 elif h_class in (Subquery, Exists): # Subquery allows QuerySet & Query
158 return side.query.query if side.query.__class__ is QuerySet else side.query
159 elif h_class in UNCACHABLE_FUNCS:
160 raise UncachableQuery
161
162
163 def _find_subqueries_in_where(children):
164 for child in children:
165 child_class = child.__class__
166 if child_class is WhereNode:
167 for grand_child in _find_subqueries_in_where(child.children):
168 yield grand_child
169 elif child_class is ExtraWhere:
170 raise IsRawQuery
171 elif child_class is NothingNode:
172 pass
173 else:
174 try:
175 child_rhs = child.rhs
176 child_lhs = child.lhs
177 except AttributeError:
178 raise UncachableQuery
179 rhs = _find_rhs_lhs_subquery(child_rhs)
180 if rhs is not None:
181 yield rhs
182 lhs = _find_rhs_lhs_subquery(child_lhs)
183 if lhs is not None:
184 yield lhs
185
186
187 def is_cachable(table):
188 whitelist = cachalot_settings.CACHALOT_ONLY_CACHABLE_TABLES
189 if whitelist and table not in whitelist:
190 return False
191 return table not in cachalot_settings.CACHALOT_UNCACHABLE_TABLES
192
193
194 def are_all_cachable(tables):
195 whitelist = cachalot_settings.CACHALOT_ONLY_CACHABLE_TABLES
196 if whitelist and not tables.issubset(whitelist):
197 return False
198 return tables.isdisjoint(cachalot_settings.CACHALOT_UNCACHABLE_TABLES)
199
200
201 def filter_cachable(tables):
202 whitelist = cachalot_settings.CACHALOT_ONLY_CACHABLE_TABLES
203 tables = tables.difference(cachalot_settings.CACHALOT_UNCACHABLE_TABLES)
204 if whitelist:
205 return tables.intersection(whitelist)
206 return tables
207
208
209 def _flatten(expression: 'BaseExpression'):
210 """
211 Recursively yield this expression and all subexpressions, in
212 depth-first order.
213
214 Taken from Django 3.2 as the previous Django versions don’t check
215 for existence of flatten.
216 """
217 yield expression
218 for expr in expression.get_source_expressions():
219 if expr:
220 if hasattr(expr, 'flatten'):
221 yield from _flatten(expr)
222 else:
223 yield expr
224
225
226 def _get_tables(db_alias, query, compiler=False):
227 from django.db import connections
228
229 if query.select_for_update or (
230 not cachalot_settings.CACHALOT_CACHE_RANDOM
231 and '?' in query.order_by):
232 raise UncachableQuery
233
234 try:
235 if query.extra_select:
236 raise IsRawQuery
237
238 # Gets all tables already found by the ORM.
239 tables = set(query.table_map)
240 if query.get_meta():
241 tables.add(query.get_meta().db_table)
242
243 # Gets tables in subquery annotations.
244 for annotation in query.annotations.values():
245 if type(annotation) in UNCACHABLE_FUNCS:
246 raise UncachableQuery
247 for expression in _flatten(annotation):
248 if isinstance(expression, Subquery):
249 # Django 2.2 only: no query, only queryset
250 if not hasattr(expression, 'query'):
251 tables.update(_get_tables(db_alias, expression.queryset.query))
252 # Django 3+
253 else:
254 tables.update(_get_tables(db_alias, expression.query))
255 # Django 6.0+: Subquery.resolve_expression() returns Query directly
256 # with subquery=True attribute instead of Subquery wrapper
257 elif isinstance(expression, Query) and getattr(expression, 'subquery', False):
258 tables.update(_get_tables(db_alias, expression))
259 elif isinstance(expression, RawSQL):
260 sql = expression.as_sql(None, None)[0].lower()
261 tables.update(_get_tables_from_sql(connections[db_alias], sql))
262 # Gets tables in WHERE subqueries.
263 for subquery in _find_subqueries_in_where(query.where.children):
264 tables.update(_get_tables(db_alias, subquery))
265 # Gets tables in HAVING subqueries.
266 if isinstance(query, AggregateQuery):
267 try:
268 tables.update(_get_tables_from_sql(connections[db_alias], query.subquery))
269 except TypeError: # For Django 3.2+
270 tables.update(_get_tables(db_alias, query.inner_query))
271 # Gets tables in combined queries
272 # using `.union`, `.intersection`, or `difference`.
273 if query.combined_queries:
274 for combined_query in query.combined_queries:
275 tables.update(_get_tables(db_alias, combined_query))
276 except IsRawQuery:
277 sql = query.get_compiler(db_alias).as_sql()[0].lower()
278 tables = _get_tables_from_sql(connections[db_alias], sql)
279 else:
280 # Additional check of the final SQL.
281 # Potentially overlooked tables are added here. Tables may be overlooked by the regular checks
282 # as not all expressions are handled yet. This final check acts as safety net.
283 if cachalot_settings.CACHALOT_FINAL_SQL_CHECK:
284 if compiler:
285 # Access generated SQL stored when caching the query!
286 sql = compiler.__cachalot_generated_sql
287 else:
288 sql = query.get_compiler(db_alias).as_sql()[0].lower()
289 final_check_tables = _get_tables_from_sql(connections[db_alias], sql, enable_quote=True)
290 tables.update(final_check_tables)
291
292 if not are_all_cachable(tables):
293 raise UncachableQuery
294 return tables
295
296
297 def _get_table_cache_keys(compiler):
298 db_alias = compiler.using
299 get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN
300 return [get_table_cache_key(db_alias, t)
301 for t in _get_tables(db_alias, compiler.query, compiler)]
302
303
304 def _invalidate_tables(cache, db_alias, tables):
305 tables = filter_cachable(set(tables))
306 if not tables:
307 return
308 now = time()
309 get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN
310 cache.set_many(
311 {get_table_cache_key(db_alias, t): now for t in tables},
312 cachalot_settings.CACHALOT_TIMEOUT)
313
314 if isinstance(cache, AtomicCache):
315 cache.to_be_invalidated.update(tables)