query_utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. """
  2. Various data structures used in query construction.
  3. Factored out from django.db.models.query to avoid making the main module very
  4. large and/or so that they can be used by other modules without getting into
  5. circular import difficulties.
  6. """
  7. import functools
  8. import inspect
  9. import logging
  10. from collections import namedtuple
  11. from django.core.exceptions import FieldError
  12. from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections
  13. from django.db.models.constants import LOOKUP_SEP
  14. from django.utils import tree
  15. from django.utils.functional import cached_property
  16. from django.utils.hashable import make_hashable
  17. logger = logging.getLogger("django.db.models")
  18. # PathInfo is used when converting lookups (fk__somecol). The contents
  19. # describe the relation in Model terms (model Options and Fields for both
  20. # sides of the relation. The join_field is the field backing the relation.
  21. PathInfo = namedtuple(
  22. "PathInfo",
  23. "from_opts to_opts target_fields join_field m2m direct filtered_relation",
  24. )
  25. def subclasses(cls):
  26. yield cls
  27. for subclass in cls.__subclasses__():
  28. yield from subclasses(subclass)
  29. class Q(tree.Node):
  30. """
  31. Encapsulate filters as objects that can then be combined logically (using
  32. `&` and `|`).
  33. """
  34. # Connection types
  35. AND = "AND"
  36. OR = "OR"
  37. XOR = "XOR"
  38. default = AND
  39. conditional = True
  40. def __init__(self, *args, _connector=None, _negated=False, **kwargs):
  41. super().__init__(
  42. children=[*args, *sorted(kwargs.items())],
  43. connector=_connector,
  44. negated=_negated,
  45. )
  46. def _combine(self, other, conn):
  47. if getattr(other, "conditional", False) is False:
  48. raise TypeError(other)
  49. if not self:
  50. return other.copy()
  51. if not other and isinstance(other, Q):
  52. return self.copy()
  53. obj = self.create(connector=conn)
  54. obj.add(self, conn)
  55. obj.add(other, conn)
  56. return obj
  57. def __or__(self, other):
  58. return self._combine(other, self.OR)
  59. def __and__(self, other):
  60. return self._combine(other, self.AND)
  61. def __xor__(self, other):
  62. return self._combine(other, self.XOR)
  63. def __invert__(self):
  64. obj = self.copy()
  65. obj.negate()
  66. return obj
  67. def resolve_expression(
  68. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  69. ):
  70. # We must promote any new joins to left outer joins so that when Q is
  71. # used as an expression, rows aren't filtered due to joins.
  72. clause, joins = query._add_q(
  73. self,
  74. reuse,
  75. allow_joins=allow_joins,
  76. split_subq=False,
  77. check_filterable=False,
  78. summarize=summarize,
  79. )
  80. query.promote_joins(joins)
  81. return clause
  82. def flatten(self):
  83. """
  84. Recursively yield this Q object and all subexpressions, in depth-first
  85. order.
  86. """
  87. yield self
  88. for child in self.children:
  89. if isinstance(child, tuple):
  90. # Use the lookup.
  91. child = child[1]
  92. if hasattr(child, "flatten"):
  93. yield from child.flatten()
  94. else:
  95. yield child
  96. def check(self, against, using=DEFAULT_DB_ALIAS):
  97. """
  98. Do a database query to check if the expressions of the Q instance
  99. matches against the expressions.
  100. """
  101. # Avoid circular imports.
  102. from django.db.models import BooleanField, Value
  103. from django.db.models.functions import Coalesce
  104. from django.db.models.sql import Query
  105. from django.db.models.sql.constants import SINGLE
  106. query = Query(None)
  107. for name, value in against.items():
  108. if not hasattr(value, "resolve_expression"):
  109. value = Value(value)
  110. query.add_annotation(value, name, select=False)
  111. query.add_annotation(Value(1), "_check")
  112. # This will raise a FieldError if a field is missing in "against".
  113. if connections[using].features.supports_comparing_boolean_expr:
  114. query.add_q(Q(Coalesce(self, True, output_field=BooleanField())))
  115. else:
  116. query.add_q(self)
  117. compiler = query.get_compiler(using=using)
  118. try:
  119. return compiler.execute_sql(SINGLE) is not None
  120. except DatabaseError as e:
  121. logger.warning("Got a database error calling check() on %r: %s", self, e)
  122. return True
  123. def deconstruct(self):
  124. path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
  125. if path.startswith("django.db.models.query_utils"):
  126. path = path.replace("django.db.models.query_utils", "django.db.models")
  127. args = tuple(self.children)
  128. kwargs = {}
  129. if self.connector != self.default:
  130. kwargs["_connector"] = self.connector
  131. if self.negated:
  132. kwargs["_negated"] = True
  133. return path, args, kwargs
  134. @cached_property
  135. def identity(self):
  136. path, args, kwargs = self.deconstruct()
  137. identity = [path, *kwargs.items()]
  138. for child in args:
  139. if isinstance(child, tuple):
  140. arg, value = child
  141. value = make_hashable(value)
  142. identity.append((arg, value))
  143. else:
  144. identity.append(child)
  145. return tuple(identity)
  146. def __eq__(self, other):
  147. if not isinstance(other, Q):
  148. return NotImplemented
  149. return other.identity == self.identity
  150. def __hash__(self):
  151. return hash(self.identity)
  152. @cached_property
  153. def referenced_base_fields(self):
  154. """
  155. Retrieve all base fields referenced directly or through F expressions
  156. excluding any fields referenced through joins.
  157. """
  158. # Avoid circular imports.
  159. from django.db.models.sql import query
  160. return {
  161. child.split(LOOKUP_SEP, 1)[0] for child in query.get_children_from_q(self)
  162. }
  163. class DeferredAttribute:
  164. """
  165. A wrapper for a deferred-loading field. When the value is read from this
  166. object the first time, the query is executed.
  167. """
  168. def __init__(self, field):
  169. self.field = field
  170. def __get__(self, instance, cls=None):
  171. """
  172. Retrieve and caches the value from the datastore on the first lookup.
  173. Return the cached value.
  174. """
  175. if instance is None:
  176. return self
  177. data = instance.__dict__
  178. field_name = self.field.attname
  179. if field_name not in data:
  180. # Let's see if the field is part of the parent chain. If so we
  181. # might be able to reuse the already loaded value. Refs #18343.
  182. val = self._check_parent_chain(instance)
  183. if val is None:
  184. if instance.pk is None and self.field.generated:
  185. raise AttributeError(
  186. "Cannot read a generated field from an unsaved model."
  187. )
  188. instance.refresh_from_db(fields=[field_name])
  189. else:
  190. data[field_name] = val
  191. return data[field_name]
  192. def _check_parent_chain(self, instance):
  193. """
  194. Check if the field value can be fetched from a parent field already
  195. loaded in the instance. This can be done if the to-be fetched
  196. field is a primary key field.
  197. """
  198. opts = instance._meta
  199. link_field = opts.get_ancestor_link(self.field.model)
  200. if self.field.primary_key and self.field != link_field:
  201. return getattr(instance, link_field.attname)
  202. return None
  203. class class_or_instance_method:
  204. """
  205. Hook used in RegisterLookupMixin to return partial functions depending on
  206. the caller type (instance or class of models.Field).
  207. """
  208. def __init__(self, class_method, instance_method):
  209. self.class_method = class_method
  210. self.instance_method = instance_method
  211. def __get__(self, instance, owner):
  212. if instance is None:
  213. return functools.partial(self.class_method, owner)
  214. return functools.partial(self.instance_method, instance)
  215. class RegisterLookupMixin:
  216. def _get_lookup(self, lookup_name):
  217. return self.get_lookups().get(lookup_name, None)
  218. @functools.cache
  219. def get_class_lookups(cls):
  220. class_lookups = [
  221. parent.__dict__.get("class_lookups", {}) for parent in inspect.getmro(cls)
  222. ]
  223. return cls.merge_dicts(class_lookups)
  224. def get_instance_lookups(self):
  225. class_lookups = self.get_class_lookups()
  226. if instance_lookups := getattr(self, "instance_lookups", None):
  227. return {**class_lookups, **instance_lookups}
  228. return class_lookups
  229. get_lookups = class_or_instance_method(get_class_lookups, get_instance_lookups)
  230. get_class_lookups = classmethod(get_class_lookups)
  231. def get_lookup(self, lookup_name):
  232. from django.db.models.lookups import Lookup
  233. found = self._get_lookup(lookup_name)
  234. if found is None and hasattr(self, "output_field"):
  235. return self.output_field.get_lookup(lookup_name)
  236. if found is not None and not issubclass(found, Lookup):
  237. return None
  238. return found
  239. def get_transform(self, lookup_name):
  240. from django.db.models.lookups import Transform
  241. found = self._get_lookup(lookup_name)
  242. if found is None and hasattr(self, "output_field"):
  243. return self.output_field.get_transform(lookup_name)
  244. if found is not None and not issubclass(found, Transform):
  245. return None
  246. return found
  247. @staticmethod
  248. def merge_dicts(dicts):
  249. """
  250. Merge dicts in reverse to preference the order of the original list. e.g.,
  251. merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
  252. """
  253. merged = {}
  254. for d in reversed(dicts):
  255. merged.update(d)
  256. return merged
  257. @classmethod
  258. def _clear_cached_class_lookups(cls):
  259. for subclass in subclasses(cls):
  260. subclass.get_class_lookups.cache_clear()
  261. def register_class_lookup(cls, lookup, lookup_name=None):
  262. if lookup_name is None:
  263. lookup_name = lookup.lookup_name
  264. if "class_lookups" not in cls.__dict__:
  265. cls.class_lookups = {}
  266. cls.class_lookups[lookup_name] = lookup
  267. cls._clear_cached_class_lookups()
  268. return lookup
  269. def register_instance_lookup(self, lookup, lookup_name=None):
  270. if lookup_name is None:
  271. lookup_name = lookup.lookup_name
  272. if "instance_lookups" not in self.__dict__:
  273. self.instance_lookups = {}
  274. self.instance_lookups[lookup_name] = lookup
  275. return lookup
  276. register_lookup = class_or_instance_method(
  277. register_class_lookup, register_instance_lookup
  278. )
  279. register_class_lookup = classmethod(register_class_lookup)
  280. def _unregister_class_lookup(cls, lookup, lookup_name=None):
  281. """
  282. Remove given lookup from cls lookups. For use in tests only as it's
  283. not thread-safe.
  284. """
  285. if lookup_name is None:
  286. lookup_name = lookup.lookup_name
  287. del cls.class_lookups[lookup_name]
  288. cls._clear_cached_class_lookups()
  289. def _unregister_instance_lookup(self, lookup, lookup_name=None):
  290. """
  291. Remove given lookup from instance lookups. For use in tests only as
  292. it's not thread-safe.
  293. """
  294. if lookup_name is None:
  295. lookup_name = lookup.lookup_name
  296. del self.instance_lookups[lookup_name]
  297. _unregister_lookup = class_or_instance_method(
  298. _unregister_class_lookup, _unregister_instance_lookup
  299. )
  300. _unregister_class_lookup = classmethod(_unregister_class_lookup)
  301. def select_related_descend(field, restricted, requested, select_mask):
  302. """
  303. Return whether `field` should be used to descend deeper for
  304. `select_related()` purposes.
  305. Arguments:
  306. * `field` - the field to be checked. Can be either a `Field` or
  307. `ForeignObjectRel` instance.
  308. * `restricted` - a boolean field, indicating if the field list has been
  309. manually restricted using a select_related() clause.
  310. * `requested` - the select_related() dictionary.
  311. * `select_mask` - the dictionary of selected fields.
  312. """
  313. # Only relationships can be descended.
  314. if not field.remote_field:
  315. return False
  316. # Forward MTI parent links should not be explicitly descended as they are
  317. # always JOIN'ed against (unless excluded by `select_mask`).
  318. if getattr(field.remote_field, "parent_link", False):
  319. return False
  320. # When `select_related()` is used without a `*requested` mask all
  321. # relationships are descended unless they are nullable.
  322. if not restricted:
  323. return not field.null
  324. # When `select_related(*requested)` is used only fields that are part of
  325. # `requested` should be descended.
  326. if field.name not in requested:
  327. return False
  328. # Prevent invalid usages of `select_related()` and `only()`/`defer()` such
  329. # as `select_related("a").only("b")` and `select_related("a").defer("a")`.
  330. if select_mask and field not in select_mask:
  331. raise FieldError(
  332. f"Field {field.model._meta.object_name}.{field.name} cannot be both "
  333. "deferred and traversed using select_related at the same time."
  334. )
  335. return True
  336. def refs_expression(lookup_parts, annotations):
  337. """
  338. Check if the lookup_parts contains references to the given annotations set.
  339. Because the LOOKUP_SEP is contained in the default annotation names, check
  340. each prefix of the lookup_parts for a match.
  341. """
  342. for n in range(1, len(lookup_parts) + 1):
  343. level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n])
  344. if annotations.get(level_n_lookup):
  345. return level_n_lookup, lookup_parts[n:]
  346. return None, ()
  347. def check_rel_lookup_compatibility(model, target_opts, field):
  348. """
  349. Check that self.model is compatible with target_opts. Compatibility
  350. is OK if:
  351. 1) model and opts match (where proxy inheritance is removed)
  352. 2) model is parent of opts' model or the other way around
  353. """
  354. def check(opts):
  355. return (
  356. model._meta.concrete_model == opts.concrete_model
  357. or opts.concrete_model in model._meta.all_parents
  358. or model in opts.all_parents
  359. )
  360. # If the field is a primary key, then doing a query against the field's
  361. # model is ok, too. Consider the case:
  362. # class Restaurant(models.Model):
  363. # place = OneToOneField(Place, primary_key=True):
  364. # Restaurant.objects.filter(pk__in=Restaurant.objects.all()).
  365. # If we didn't have the primary key check, then pk__in (== place__in) would
  366. # give Place's opts as the target opts, but Restaurant isn't compatible
  367. # with that. This logic applies only to primary keys, as when doing __in=qs,
  368. # we are going to turn this into __in=qs.values('pk') later on.
  369. return check(target_opts) or (
  370. getattr(field, "primary_key", False) and check(field.model._meta)
  371. )
  372. class FilteredRelation:
  373. """Specify custom filtering in the ON clause of SQL joins."""
  374. def __init__(self, relation_name, *, condition=Q()):
  375. if not relation_name:
  376. raise ValueError("relation_name cannot be empty.")
  377. self.relation_name = relation_name
  378. self.alias = None
  379. if not isinstance(condition, Q):
  380. raise ValueError("condition argument must be a Q() instance.")
  381. # .condition and .resolved_condition have to be stored independently
  382. # as the former must remain unchanged for Join.__eq__ to remain stable
  383. # and reusable even once their .filtered_relation are resolved.
  384. self.condition = condition
  385. self.resolved_condition = None
  386. def __eq__(self, other):
  387. if not isinstance(other, self.__class__):
  388. return NotImplemented
  389. return (
  390. self.relation_name == other.relation_name
  391. and self.alias == other.alias
  392. and self.condition == other.condition
  393. )
  394. def clone(self):
  395. clone = FilteredRelation(self.relation_name, condition=self.condition)
  396. clone.alias = self.alias
  397. if (resolved_condition := self.resolved_condition) is not None:
  398. clone.resolved_condition = resolved_condition.clone()
  399. return clone
  400. def relabeled_clone(self, change_map):
  401. clone = self.clone()
  402. if resolved_condition := clone.resolved_condition:
  403. clone.resolved_condition = resolved_condition.relabeled_clone(change_map)
  404. return clone
  405. def resolve_expression(self, query, reuse, *args, **kwargs):
  406. clone = self.clone()
  407. clone.resolved_condition = query.build_filter(
  408. self.condition,
  409. can_reuse=reuse,
  410. allow_joins=True,
  411. split_subq=False,
  412. update_join_types=False,
  413. )[0]
  414. return clone
  415. def as_sql(self, compiler, connection):
  416. return compiler.compile(self.resolved_condition)