query.py 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897
  1. """
  2. Create SQL statements for QuerySets.
  3. The code in here encapsulates all of the SQL construction so that QuerySets
  4. themselves do not have to (and could be backed by things other than SQL
  5. databases). The abstraction barrier only works one way: this module has to know
  6. all about the internals of models in order to get the information it needs.
  7. """
  8. import copy
  9. import difflib
  10. import functools
  11. import sys
  12. import warnings
  13. from collections import Counter, namedtuple
  14. from collections.abc import Iterable, Iterator, Mapping
  15. from itertools import chain, count, product
  16. from string import ascii_uppercase
  17. from django.core.exceptions import FieldDoesNotExist, FieldError
  18. from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections
  19. from django.db.models.aggregates import Count
  20. from django.db.models.constants import LOOKUP_SEP
  21. from django.db.models.expressions import (
  22. BaseExpression,
  23. Col,
  24. ColPairs,
  25. Exists,
  26. F,
  27. OuterRef,
  28. RawSQL,
  29. Ref,
  30. ResolvedOuterRef,
  31. Value,
  32. )
  33. from django.db.models.fields import Field
  34. from django.db.models.lookups import Lookup
  35. from django.db.models.query_utils import (
  36. Q,
  37. check_rel_lookup_compatibility,
  38. refs_expression,
  39. )
  40. from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
  41. from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin
  42. from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode
  43. from django.utils.deprecation import RemovedInDjango70Warning, django_file_prefixes
  44. from django.utils.functional import cached_property
  45. from django.utils.regex_helper import _lazy_re_compile
  46. from django.utils.tree import Node
  47. __all__ = ["Query", "RawQuery"]
  48. # RemovedInDjango70Warning: When the deprecation ends, replace with:
  49. # Quotation marks ('"`[]), whitespace characters, control characters,
  50. # semicolons, percent signs, hashes, or inline SQL comments are
  51. # forbidden in column aliases.
  52. # FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(
  53. # r"['`\"\]\[;\s\x00-\x1F\x7F-\x9F]|%|#|--|/\*|\*/"
  54. # )
  55. # Quotation marks ('"`[]), whitespace characters, control characters,
  56. # semicolons, hashes, or inline SQL comments are forbidden in column aliases.
  57. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(
  58. r"['`\"\]\[;\s\x00-\x1F\x7F-\x9F]|#|--|/\*|\*/"
  59. )
  60. # Inspired from
  61. # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
  62. EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w-]+")
  63. def get_field_names_from_opts(opts):
  64. if opts is None:
  65. return set()
  66. return set(
  67. chain.from_iterable(
  68. (f.name, f.attname) if f.concrete else (f.name,) for f in opts.get_fields()
  69. )
  70. )
  71. def get_paths_from_expression(expr):
  72. if isinstance(expr, F):
  73. yield expr.name
  74. elif hasattr(expr, "flatten"):
  75. for child in expr.flatten():
  76. if isinstance(child, F):
  77. yield child.name
  78. elif isinstance(child, Q):
  79. yield from get_children_from_q(child)
  80. def get_children_from_q(q):
  81. for child in q.children:
  82. if isinstance(child, Node):
  83. yield from get_children_from_q(child)
  84. elif isinstance(child, tuple):
  85. lhs, rhs = child
  86. yield lhs
  87. if hasattr(rhs, "resolve_expression"):
  88. yield from get_paths_from_expression(rhs)
  89. elif hasattr(child, "resolve_expression"):
  90. yield from get_paths_from_expression(child)
  91. def get_child_with_renamed_prefix(prefix, replacement, child):
  92. from django.db.models.query import QuerySet
  93. if isinstance(child, Node):
  94. return rename_prefix_from_q(prefix, replacement, child)
  95. if isinstance(child, tuple):
  96. lhs, rhs = child
  97. if lhs.startswith(prefix + LOOKUP_SEP):
  98. lhs = lhs.replace(prefix, replacement, 1)
  99. if not isinstance(rhs, F) and hasattr(rhs, "resolve_expression"):
  100. rhs = get_child_with_renamed_prefix(prefix, replacement, rhs)
  101. return lhs, rhs
  102. if isinstance(child, F):
  103. child = child.copy()
  104. if child.name.startswith(prefix + LOOKUP_SEP):
  105. child.name = child.name.replace(prefix, replacement, 1)
  106. elif isinstance(child, QuerySet):
  107. # QuerySet may contain OuterRef() references which cannot work properly
  108. # without repointing to the filtered annotation and will spawn a
  109. # different JOIN. Always raise ValueError instead of providing partial
  110. # support in other cases.
  111. raise ValueError(
  112. "Passing a QuerySet within a FilteredRelation is not supported."
  113. )
  114. elif hasattr(child, "resolve_expression"):
  115. child = child.copy()
  116. child.set_source_expressions(
  117. [
  118. get_child_with_renamed_prefix(prefix, replacement, grand_child)
  119. for grand_child in child.get_source_expressions()
  120. ]
  121. )
  122. return child
  123. def rename_prefix_from_q(prefix, replacement, q):
  124. return Q.create(
  125. [get_child_with_renamed_prefix(prefix, replacement, c) for c in q.children],
  126. q.connector,
  127. q.negated,
  128. )
  129. JoinInfo = namedtuple(
  130. "JoinInfo",
  131. ("final_field", "targets", "opts", "joins", "path", "transform_function"),
  132. )
  133. class RawQuery:
  134. """A single raw SQL query."""
  135. def __init__(self, sql, using, params=()):
  136. self.params = params
  137. self.sql = sql
  138. self.using = using
  139. self.cursor = None
  140. # Mirror some properties of a normal query so that
  141. # the compiler can be used to process results.
  142. self.low_mark, self.high_mark = 0, None # Used for offset/limit
  143. self.extra_select = {}
  144. self.annotation_select = {}
  145. def chain(self, using):
  146. return self.clone(using)
  147. def clone(self, using):
  148. return RawQuery(self.sql, using, params=self.params)
  149. def get_columns(self):
  150. if self.cursor is None:
  151. self._execute_query()
  152. converter = connections[self.using].introspection.identifier_converter
  153. return [converter(column_meta[0]) for column_meta in self.cursor.description]
  154. def __iter__(self):
  155. # Always execute a new query for a new iterator.
  156. # This could be optimized with a cache at the expense of RAM.
  157. self._execute_query()
  158. if not connections[self.using].features.can_use_chunked_reads:
  159. # If the database can't use chunked reads we need to make sure we
  160. # evaluate the entire query up front.
  161. result = list(self.cursor)
  162. else:
  163. result = self.cursor
  164. return iter(result)
  165. def __repr__(self):
  166. return "<%s: %s>" % (self.__class__.__name__, self)
  167. @property
  168. def params_type(self):
  169. if self.params is None:
  170. return None
  171. return dict if isinstance(self.params, Mapping) else tuple
  172. def __str__(self):
  173. if self.params_type is None:
  174. return self.sql
  175. return self.sql % self.params_type(self.params)
  176. def _execute_query(self):
  177. connection = connections[self.using]
  178. # Adapt parameters to the database, as much as possible considering
  179. # that the target type isn't known. See #17755.
  180. params_type = self.params_type
  181. adapter = connection.ops.adapt_unknown_value
  182. if params_type is tuple:
  183. params = tuple(adapter(val) for val in self.params)
  184. elif params_type is dict:
  185. params = {key: adapter(val) for key, val in self.params.items()}
  186. elif params_type is None:
  187. params = None
  188. else:
  189. raise RuntimeError("Unexpected params type: %s" % params_type)
  190. self.cursor = connection.cursor()
  191. self.cursor.execute(self.sql, params)
  192. ExplainInfo = namedtuple("ExplainInfo", ("format", "options"))
  193. class Query(BaseExpression):
  194. """A single SQL query."""
  195. alias_prefix = "T"
  196. empty_result_set_value = None
  197. subq_aliases = frozenset([alias_prefix])
  198. compiler = "SQLCompiler"
  199. base_table_class = BaseTable
  200. join_class = Join
  201. default_cols = True
  202. default_ordering = True
  203. standard_ordering = True
  204. filter_is_sticky = False
  205. subquery = False
  206. contains_subquery = False
  207. # SQL-related attributes.
  208. # Select and related select clauses are expressions to use in the SELECT
  209. # clause of the query. The select is used for cases where we want to set up
  210. # the select clause to contain other than default fields (values(),
  211. # subqueries...). Note that annotations go to annotations dictionary.
  212. select = ()
  213. # The group_by attribute can have one of the following forms:
  214. # - None: no group by at all in the query
  215. # - A tuple of expressions: group by (at least) those expressions.
  216. # String refs are also allowed for now.
  217. # - True: group by all select fields of the model
  218. # See compiler.get_group_by() for details.
  219. group_by = None
  220. order_by = ()
  221. low_mark = 0 # Used for offset/limit.
  222. high_mark = None # Used for offset/limit.
  223. distinct = False
  224. distinct_fields = ()
  225. select_for_update = False
  226. select_for_update_nowait = False
  227. select_for_update_skip_locked = False
  228. select_for_update_of = ()
  229. select_for_no_key_update = False
  230. select_related = False
  231. # Arbitrary limit for select_related to prevents infinite recursion.
  232. max_depth = 5
  233. # Holds the selects defined by a call to values() or values_list()
  234. # excluding annotation_select and extra_select.
  235. values_select = ()
  236. selected = None
  237. # SQL annotation-related attributes.
  238. annotation_select_mask = None
  239. _annotation_select_cache = None
  240. # Set combination attributes.
  241. combinator = None
  242. combinator_all = False
  243. combined_queries = ()
  244. # These are for extensions. The contents are more or less appended verbatim
  245. # to the appropriate clause.
  246. extra_select_mask = None
  247. _extra_select_cache = None
  248. extra_tables = ()
  249. extra_order_by = ()
  250. # A tuple that is a set of model field names and either True, if these are
  251. # the fields to defer, or False if these are the only fields to load.
  252. deferred_loading = (frozenset(), True)
  253. explain_info = None
  254. def __init__(self, model, alias_cols=True):
  255. self.model = model
  256. self.alias_refcount = {}
  257. # alias_map is the most important data structure regarding joins.
  258. # It's used for recording which joins exist in the query and what
  259. # types they are. The key is the alias of the joined table (possibly
  260. # the table name) and the value is a Join-like object (see
  261. # sql.datastructures.Join for more information).
  262. self.alias_map = {}
  263. # Whether to provide alias to columns during reference resolving.
  264. self.alias_cols = alias_cols
  265. # Sometimes the query contains references to aliases in outer queries
  266. # (as a result of split_exclude). Correct alias quoting needs to know
  267. # these aliases too. Map external tables to whether they are aliased.
  268. self.external_aliases = {}
  269. self.table_map = {} # Maps table names to list of aliases.
  270. self.used_aliases = set()
  271. self.where = WhereNode()
  272. # Maps alias -> Annotation Expression.
  273. self.annotations = {}
  274. # These are for extensions. The contents are more or less appended
  275. # verbatim to the appropriate clause.
  276. self.extra = {} # Maps col_alias -> (col_sql, params).
  277. self._filtered_relations = {}
  278. @property
  279. def output_field(self):
  280. if len(self.select) == 1:
  281. select = self.select[0]
  282. return getattr(select, "target", None) or select.field
  283. elif len(self.annotation_select) == 1:
  284. return next(iter(self.annotation_select.values())).output_field
  285. @cached_property
  286. def base_table(self):
  287. for alias in self.alias_map:
  288. return alias
  289. def __str__(self):
  290. """
  291. Return the query as a string of SQL with the parameter values
  292. substituted in (use sql_with_params() to see the unsubstituted string).
  293. Parameter values won't necessarily be quoted correctly, since that is
  294. done by the database interface at execution time.
  295. """
  296. sql, params = self.sql_with_params()
  297. return sql % params
  298. def sql_with_params(self):
  299. """
  300. Return the query as an SQL string and the parameters that will be
  301. substituted into the query.
  302. """
  303. return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
  304. def __deepcopy__(self, memo):
  305. """Limit the amount of work when a Query is deepcopied."""
  306. result = self.clone()
  307. memo[id(self)] = result
  308. return result
  309. def get_compiler(self, using=None, connection=None, elide_empty=True):
  310. if using is None and connection is None:
  311. raise ValueError("Need either using or connection")
  312. if using:
  313. connection = connections[using]
  314. return connection.ops.compiler(self.compiler)(
  315. self, connection, using, elide_empty
  316. )
  317. def get_meta(self):
  318. """
  319. Return the Options instance (the model._meta) from which to start
  320. processing. Normally, this is self.model._meta, but it can be changed
  321. by subclasses.
  322. """
  323. if self.model:
  324. return self.model._meta
  325. def clone(self):
  326. """
  327. Return a copy of the current Query. A lightweight alternative to
  328. deepcopy().
  329. """
  330. obj = Empty()
  331. obj.__class__ = self.__class__
  332. # Copy references to everything.
  333. obj.__dict__ = self.__dict__.copy()
  334. # Clone attributes that can't use shallow copy.
  335. obj.alias_refcount = self.alias_refcount.copy()
  336. obj.alias_map = self.alias_map.copy()
  337. obj.external_aliases = self.external_aliases.copy()
  338. obj.table_map = self.table_map.copy()
  339. obj.where = self.where.clone()
  340. obj.annotations = self.annotations.copy()
  341. if self.annotation_select_mask is not None:
  342. obj.annotation_select_mask = self.annotation_select_mask.copy()
  343. if self.combined_queries:
  344. obj.combined_queries = tuple(
  345. [query.clone() for query in self.combined_queries]
  346. )
  347. # _annotation_select_cache cannot be copied, as doing so breaks the
  348. # (necessary) state in which both annotations and
  349. # _annotation_select_cache point to the same underlying objects.
  350. # It will get re-populated in the cloned queryset the next time it's
  351. # used.
  352. obj._annotation_select_cache = None
  353. obj.extra = self.extra.copy()
  354. if self.extra_select_mask is not None:
  355. obj.extra_select_mask = self.extra_select_mask.copy()
  356. if self._extra_select_cache is not None:
  357. obj._extra_select_cache = self._extra_select_cache.copy()
  358. if self.select_related is not False:
  359. # Use deepcopy because select_related stores fields in nested
  360. # dicts.
  361. obj.select_related = copy.deepcopy(obj.select_related)
  362. if "subq_aliases" in self.__dict__:
  363. obj.subq_aliases = self.subq_aliases.copy()
  364. obj.used_aliases = self.used_aliases.copy()
  365. obj._filtered_relations = self._filtered_relations.copy()
  366. # Clear the cached_property, if it exists.
  367. obj.__dict__.pop("base_table", None)
  368. return obj
  369. def chain(self, klass=None):
  370. """
  371. Return a copy of the current Query that's ready for another operation.
  372. The klass argument changes the type of the Query, e.g. UpdateQuery.
  373. """
  374. obj = self.clone()
  375. if klass and obj.__class__ != klass:
  376. obj.__class__ = klass
  377. if not obj.filter_is_sticky:
  378. obj.used_aliases = set()
  379. obj.filter_is_sticky = False
  380. if hasattr(obj, "_setup_query"):
  381. obj._setup_query()
  382. return obj
  383. def relabeled_clone(self, change_map):
  384. clone = self.clone()
  385. clone.change_aliases(change_map)
  386. return clone
  387. def _get_col(self, target, field, alias):
  388. if not self.alias_cols:
  389. alias = None
  390. return target.get_col(alias, field)
  391. def get_aggregation(self, using, aggregate_exprs):
  392. """
  393. Return the dictionary with the values of the existing aggregations.
  394. """
  395. if not aggregate_exprs:
  396. return {}
  397. # Store annotation mask prior to temporarily adding aggregations for
  398. # resolving purpose to facilitate their subsequent removal.
  399. refs_subquery = False
  400. refs_window = False
  401. replacements = {}
  402. annotation_select_mask = self.annotation_select_mask
  403. for alias, aggregate_expr in aggregate_exprs.items():
  404. self.check_alias(alias)
  405. aggregate = aggregate_expr.resolve_expression(
  406. self, allow_joins=True, reuse=None, summarize=True
  407. )
  408. if not aggregate.contains_aggregate:
  409. raise TypeError("%s is not an aggregate expression" % alias)
  410. # Temporarily add aggregate to annotations to allow remaining
  411. # members of `aggregates` to resolve against each others.
  412. self.append_annotation_mask([alias])
  413. aggregate_refs = aggregate.get_refs()
  414. refs_subquery |= any(
  415. getattr(self.annotations[ref], "contains_subquery", False)
  416. for ref in aggregate_refs
  417. )
  418. refs_window |= any(
  419. getattr(self.annotations[ref], "contains_over_clause", True)
  420. for ref in aggregate_refs
  421. )
  422. aggregate = aggregate.replace_expressions(replacements)
  423. self.annotations[alias] = aggregate
  424. replacements[Ref(alias, aggregate)] = aggregate
  425. # Stash resolved aggregates now that they have been allowed to resolve
  426. # against each other.
  427. aggregates = {alias: self.annotations.pop(alias) for alias in aggregate_exprs}
  428. self.set_annotation_mask(annotation_select_mask)
  429. # Existing usage of aggregation can be determined by the presence of
  430. # selected aggregates but also by filters against aliased aggregates.
  431. _, having, qualify = self.where.split_having_qualify()
  432. has_existing_aggregation = (
  433. any(
  434. getattr(annotation, "contains_aggregate", True)
  435. for annotation in self.annotations.values()
  436. )
  437. or having
  438. )
  439. set_returning_annotations = {
  440. alias
  441. for alias, annotation in self.annotation_select.items()
  442. if getattr(annotation, "set_returning", False)
  443. }
  444. # Decide if we need to use a subquery.
  445. #
  446. # Existing aggregations would cause incorrect results as
  447. # get_aggregation() must produce just one result and thus must not use
  448. # GROUP BY.
  449. #
  450. # If the query has limit or distinct, or uses set operations, then
  451. # those operations must be done in a subquery so that the query
  452. # aggregates on the limit and/or distinct results instead of applying
  453. # the distinct and limit after the aggregation.
  454. if (
  455. isinstance(self.group_by, tuple)
  456. or self.is_sliced
  457. or has_existing_aggregation
  458. or refs_subquery
  459. or refs_window
  460. or qualify
  461. or self.distinct
  462. or self.combinator
  463. or set_returning_annotations
  464. ):
  465. from django.db.models.sql.subqueries import AggregateQuery
  466. inner_query = self.clone()
  467. inner_query.subquery = True
  468. outer_query = AggregateQuery(self.model, inner_query)
  469. inner_query.select_for_update = False
  470. inner_query.select_related = False
  471. inner_query.set_annotation_mask(self.annotation_select)
  472. # Queries with distinct_fields need ordering and when a limit is
  473. # applied we must take the slice from the ordered query. Otherwise
  474. # no need for ordering.
  475. if inner_query.orderby_issubset_groupby:
  476. inner_query.clear_ordering(force=False)
  477. if not inner_query.distinct:
  478. # If the inner query uses default select and it has some
  479. # aggregate annotations, then we must make sure the inner
  480. # query is grouped by the main model's primary key. However,
  481. # clearing the select clause can alter results if distinct is
  482. # used.
  483. if inner_query.default_cols and has_existing_aggregation:
  484. inner_query.group_by = (
  485. self.model._meta.pk.get_col(inner_query.get_initial_alias()),
  486. )
  487. inner_query.default_cols = False
  488. if not qualify and not self.combinator:
  489. # Mask existing annotations that are not referenced by
  490. # aggregates to be pushed to the outer query unless
  491. # filtering against window functions or if the query is
  492. # combined as both would require complex realiasing logic.
  493. annotation_mask = set()
  494. if isinstance(self.group_by, tuple):
  495. for expr in self.group_by:
  496. annotation_mask |= expr.get_refs()
  497. for aggregate in aggregates.values():
  498. annotation_mask |= aggregate.get_refs()
  499. # Avoid eliding expressions that might have an incidence on
  500. # the implicit grouping logic.
  501. for annotation_alias, annotation in self.annotation_select.items():
  502. if annotation.get_group_by_cols():
  503. annotation_mask.add(annotation_alias)
  504. inner_query.set_annotation_mask(annotation_mask)
  505. # Annotations that possibly return multiple rows cannot
  506. # be masked as they might have an incidence on the query.
  507. annotation_mask |= set_returning_annotations
  508. # Add aggregates to the outer AggregateQuery. This requires making
  509. # sure all columns referenced by the aggregates are selected in the
  510. # inner query. It is achieved by retrieving all column references
  511. # by the aggregates, explicitly selecting them in the inner query,
  512. # and making sure the aggregates are repointed to them.
  513. col_refs = {}
  514. for alias, aggregate in aggregates.items():
  515. replacements = {}
  516. for col in self._gen_cols([aggregate], resolve_refs=False):
  517. if not (col_ref := col_refs.get(col)):
  518. index = len(col_refs) + 1
  519. col_alias = f"__col{index}"
  520. col_ref = Ref(col_alias, col)
  521. col_refs[col] = col_ref
  522. inner_query.add_annotation(col, col_alias)
  523. replacements[col] = col_ref
  524. outer_query.annotations[alias] = aggregate.replace_expressions(
  525. replacements
  526. )
  527. if (
  528. inner_query.select == ()
  529. and not inner_query.default_cols
  530. and not inner_query.annotation_select_mask
  531. ):
  532. # In case of Model.objects[0:3].count(), there would be no
  533. # field selected in the inner query, yet we must use a
  534. # subquery. So, make sure at least one field is selected.
  535. inner_query.select = (
  536. self.model._meta.pk.get_col(inner_query.get_initial_alias()),
  537. )
  538. else:
  539. outer_query = self
  540. self.select = ()
  541. self.selected = None
  542. self.default_cols = False
  543. self.extra = {}
  544. if self.annotations:
  545. # Inline reference to existing annotations and mask them as
  546. # they are unnecessary given only the summarized aggregations
  547. # are requested.
  548. replacements = {
  549. Ref(alias, annotation): annotation
  550. for alias, annotation in self.annotations.items()
  551. }
  552. self.annotations = {
  553. alias: aggregate.replace_expressions(replacements)
  554. for alias, aggregate in aggregates.items()
  555. }
  556. else:
  557. self.annotations = aggregates
  558. self.set_annotation_mask(aggregates)
  559. empty_set_result = [
  560. expression.empty_result_set_value
  561. for expression in outer_query.annotation_select.values()
  562. ]
  563. elide_empty = not any(result is NotImplemented for result in empty_set_result)
  564. outer_query.clear_ordering(force=True)
  565. outer_query.clear_limits()
  566. outer_query.select_for_update = False
  567. outer_query.select_related = False
  568. compiler = outer_query.get_compiler(using, elide_empty=elide_empty)
  569. result = compiler.execute_sql(SINGLE)
  570. if result is None:
  571. result = empty_set_result
  572. else:
  573. cols = outer_query.annotation_select.values()
  574. converters = compiler.get_converters(cols)
  575. rows = compiler.apply_converters((result,), converters)
  576. if compiler.has_composite_fields(cols):
  577. rows = compiler.composite_fields_to_tuples(rows, cols)
  578. result = next(rows)
  579. return dict(zip(outer_query.annotation_select, result))
  580. def get_count(self, using):
  581. """
  582. Perform a COUNT() query using the current filter constraints.
  583. """
  584. obj = self.clone()
  585. return obj.get_aggregation(using, {"__count": Count("*")})["__count"]
  586. def has_filters(self):
  587. return self.where
  588. def exists(self, limit=True):
  589. q = self.clone()
  590. if not (q.distinct and q.is_sliced):
  591. if q.group_by is True:
  592. q.add_fields(
  593. (f.attname for f in self.model._meta.concrete_fields), False
  594. )
  595. # Disable GROUP BY aliases to avoid orphaning references to the
  596. # SELECT clause which is about to be cleared.
  597. q.set_group_by(allow_aliases=False)
  598. q.clear_select_clause()
  599. if q.combined_queries and q.combinator == "union":
  600. q.combined_queries = tuple(
  601. combined_query.exists(limit=False)
  602. for combined_query in q.combined_queries
  603. )
  604. q.clear_ordering(force=True)
  605. if limit is True:
  606. q.set_limits(high=1)
  607. q.add_annotation(Value(1), "a")
  608. return q
  609. def has_results(self, using):
  610. q = self.exists()
  611. compiler = q.get_compiler(using=using)
  612. return compiler.has_results()
  613. def explain(self, using, format=None, **options):
  614. q = self.clone()
  615. for option_name in options:
  616. if (
  617. not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)
  618. or "--" in option_name
  619. ):
  620. raise ValueError(f"Invalid option name: {option_name!r}.")
  621. q.explain_info = ExplainInfo(format, options)
  622. compiler = q.get_compiler(using=using)
  623. return "\n".join(compiler.explain_query())
  624. def combine(self, rhs, connector):
  625. """
  626. Merge the 'rhs' query into the current one (with any 'rhs' effects
  627. being applied *after* (that is, "to the right of") anything in the
  628. current query. 'rhs' is not modified during a call to this function.
  629. The 'connector' parameter describes how to connect filters from the
  630. 'rhs' query.
  631. """
  632. if self.model != rhs.model:
  633. raise TypeError("Cannot combine queries on two different base models.")
  634. if self.is_sliced:
  635. raise TypeError("Cannot combine queries once a slice has been taken.")
  636. if self.distinct != rhs.distinct:
  637. raise TypeError("Cannot combine a unique query with a non-unique query.")
  638. if self.distinct_fields != rhs.distinct_fields:
  639. raise TypeError("Cannot combine queries with different distinct fields.")
  640. # If lhs and rhs shares the same alias prefix, it is possible to have
  641. # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up
  642. # as T4 -> T6 while combining two querysets. To prevent this, change an
  643. # alias prefix of the rhs and update current aliases accordingly,
  644. # except if the alias is the base table since it must be present in the
  645. # query on both sides.
  646. initial_alias = self.get_initial_alias()
  647. rhs = rhs.clone()
  648. rhs.bump_prefix(self, exclude={initial_alias})
  649. # Work out how to relabel the rhs aliases, if necessary.
  650. change_map = {}
  651. conjunction = connector == AND
  652. # Determine which existing joins can be reused. When combining the
  653. # query with AND we must recreate all joins for m2m filters. When
  654. # combining with OR we can reuse joins. The reason is that in AND
  655. # case a single row can't fulfill a condition like:
  656. # revrel__col=1 & revrel__col=2
  657. # But, there might be two different related rows matching this
  658. # condition. In OR case a single True is enough, so single row is
  659. # enough, too.
  660. #
  661. # Note that we will be creating duplicate joins for non-m2m joins in
  662. # the AND case. The results will be correct but this creates too many
  663. # joins. This is something that could be fixed later on.
  664. reuse = set() if conjunction else set(self.alias_map)
  665. joinpromoter = JoinPromoter(connector, 2, False)
  666. joinpromoter.add_votes(
  667. j for j in self.alias_map if self.alias_map[j].join_type == INNER
  668. )
  669. rhs_votes = set()
  670. # Now, add the joins from rhs query into the new query (skipping base
  671. # table).
  672. rhs_tables = list(rhs.alias_map)[1:]
  673. for alias in rhs_tables:
  674. join = rhs.alias_map[alias]
  675. # If the left side of the join was already relabeled, use the
  676. # updated alias.
  677. join = join.relabeled_clone(change_map)
  678. new_alias = self.join(join, reuse=reuse)
  679. if join.join_type == INNER:
  680. rhs_votes.add(new_alias)
  681. # We can't reuse the same join again in the query. If we have two
  682. # distinct joins for the same connection in rhs query, then the
  683. # combined query must have two joins, too.
  684. reuse.discard(new_alias)
  685. if alias != new_alias:
  686. change_map[alias] = new_alias
  687. if not rhs.alias_refcount[alias]:
  688. # The alias was unused in the rhs query. Unref it so that it
  689. # will be unused in the new query, too. We have to add and
  690. # unref the alias so that join promotion has information of
  691. # the join type for the unused alias.
  692. self.unref_alias(new_alias)
  693. joinpromoter.add_votes(rhs_votes)
  694. joinpromoter.update_join_types(self)
  695. # Combine subqueries aliases to ensure aliases relabelling properly
  696. # handle subqueries when combining where and select clauses.
  697. self.subq_aliases |= rhs.subq_aliases
  698. # Now relabel a copy of the rhs where-clause and add it to the current
  699. # one.
  700. w = rhs.where.clone()
  701. w.relabel_aliases(change_map)
  702. self.where.add(w, connector)
  703. # Selection columns and extra extensions are those provided by 'rhs'.
  704. if rhs.select:
  705. self.set_select([col.relabeled_clone(change_map) for col in rhs.select])
  706. else:
  707. self.select = ()
  708. if connector == OR:
  709. # It would be nice to be able to handle this, but the queries don't
  710. # really make sense (or return consistent value sets). Not worth
  711. # the extra complexity when you can write a real query instead.
  712. if self.extra and rhs.extra:
  713. raise ValueError(
  714. "When merging querysets using 'or', you cannot have "
  715. "extra(select=...) on both sides."
  716. )
  717. self.extra.update(rhs.extra)
  718. extra_select_mask = set()
  719. if self.extra_select_mask is not None:
  720. extra_select_mask.update(self.extra_select_mask)
  721. if rhs.extra_select_mask is not None:
  722. extra_select_mask.update(rhs.extra_select_mask)
  723. if extra_select_mask:
  724. self.set_extra_mask(extra_select_mask)
  725. self.extra_tables += rhs.extra_tables
  726. # Ordering uses the 'rhs' ordering, unless it has none, in which case
  727. # the current ordering is used.
  728. self.order_by = rhs.order_by or self.order_by
  729. self.extra_order_by = rhs.extra_order_by or self.extra_order_by
  730. def _get_defer_select_mask(self, opts, mask, select_mask=None):
  731. if select_mask is None:
  732. select_mask = {}
  733. select_mask[opts.pk] = {}
  734. # All concrete fields and related objects that are not part of the
  735. # defer mask must be included. If a relational field is encountered it
  736. # gets added to the mask for it be considered if `select_related` and
  737. # the cycle continues by recursively calling this function.
  738. for field in opts.concrete_fields + opts.related_objects:
  739. field_mask = mask.pop(field.name, None)
  740. field_att_mask = None
  741. if field_attname := getattr(field, "attname", None):
  742. field_att_mask = mask.pop(field_attname, None)
  743. if field_mask is None and field_att_mask is None:
  744. select_mask.setdefault(field, {})
  745. elif field_mask:
  746. if not field.is_relation:
  747. raise FieldError(next(iter(field_mask)))
  748. # Virtual fields such as many-to-many and generic foreign keys
  749. # cannot be effectively deferred. Historically, they were
  750. # allowed to be passed to QuerySet.defer(). Ignore such field
  751. # references until a layer of validation at mask alteration
  752. # time is eventually implemented.
  753. if field.many_to_many:
  754. continue
  755. field_select_mask = select_mask.setdefault(field, {})
  756. related_model = field.related_model._meta.concrete_model
  757. self._get_defer_select_mask(
  758. related_model._meta, field_mask, field_select_mask
  759. )
  760. # Remaining defer entries must be references to filtered relations
  761. # otherwise they are surfaced as missing field errors.
  762. for field_name, field_mask in mask.items():
  763. if filtered_relation := self._filtered_relations.get(field_name):
  764. relation = opts.get_field(filtered_relation.relation_name)
  765. field_select_mask = select_mask.setdefault((field_name, relation), {})
  766. related_model = relation.related_model._meta.concrete_model
  767. self._get_defer_select_mask(
  768. related_model._meta, field_mask, field_select_mask
  769. )
  770. else:
  771. opts.get_field(field_name)
  772. return select_mask
  773. def _get_only_select_mask(self, opts, mask, select_mask=None):
  774. if select_mask is None:
  775. select_mask = {}
  776. select_mask[opts.pk] = {}
  777. # Only include fields mentioned in the mask.
  778. for field_name, field_mask in mask.items():
  779. field = opts.get_field(field_name)
  780. field_select_mask = select_mask.setdefault(field, {})
  781. if field_mask:
  782. if not field.is_relation:
  783. raise FieldError(next(iter(field_mask)))
  784. related_model = field.remote_field.model._meta.concrete_model
  785. self._get_only_select_mask(
  786. related_model._meta, field_mask, field_select_mask
  787. )
  788. return select_mask
  789. def get_select_mask(self):
  790. """
  791. Convert the self.deferred_loading data structure to an alternate data
  792. structure, describing the field that *will* be loaded. This is used to
  793. compute the columns to select from the database and also by the
  794. QuerySet class to work out which fields are being initialized on each
  795. model. Models that have all their fields included aren't mentioned in
  796. the result, only those that have field restrictions in place.
  797. """
  798. field_names, defer = self.deferred_loading
  799. if not field_names:
  800. return {}
  801. mask = {}
  802. for field_name in field_names:
  803. part_mask = mask
  804. for part in field_name.split(LOOKUP_SEP):
  805. part_mask = part_mask.setdefault(part, {})
  806. opts = self.get_meta()
  807. if defer:
  808. return self._get_defer_select_mask(opts, mask)
  809. return self._get_only_select_mask(opts, mask)
  810. def table_alias(self, table_name, create=False, filtered_relation=None):
  811. """
  812. Return a table alias for the given table_name and whether this is a
  813. new alias or not.
  814. If 'create' is true, a new alias is always created. Otherwise, the
  815. most recently created alias for the table (if one exists) is reused.
  816. """
  817. alias_list = self.table_map.get(table_name)
  818. if not create and alias_list:
  819. alias = alias_list[0]
  820. self.alias_refcount[alias] += 1
  821. return alias, False
  822. # Create a new alias for this table.
  823. if alias_list:
  824. alias = "%s%d" % (self.alias_prefix, len(self.alias_map) + 1)
  825. alias_list.append(alias)
  826. else:
  827. # The first occurrence of a table uses the table name directly.
  828. alias = (
  829. filtered_relation.alias if filtered_relation is not None else table_name
  830. )
  831. self.table_map[table_name] = [alias]
  832. self.alias_refcount[alias] = 1
  833. return alias, True
  834. def ref_alias(self, alias):
  835. """Increases the reference count for this alias."""
  836. self.alias_refcount[alias] += 1
  837. def unref_alias(self, alias, amount=1):
  838. """Decreases the reference count for this alias."""
  839. self.alias_refcount[alias] -= amount
  840. def promote_joins(self, aliases):
  841. """
  842. Promote recursively the join type of given aliases and its children to
  843. an outer join. If 'unconditional' is False, only promote the join if
  844. it is nullable or the parent join is an outer join.
  845. The children promotion is done to avoid join chains that contain a
  846. LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b
  847. is promoted, then we must also promote b->c automatically, or otherwise
  848. the promotion of a->b doesn't actually change anything in the query
  849. results.
  850. """
  851. aliases = list(aliases)
  852. while aliases:
  853. alias = aliases.pop(0)
  854. if self.alias_map[alias].join_type is None:
  855. # This is the base table (first FROM entry) - this table
  856. # isn't really joined at all in the query, so we should not
  857. # alter its join type.
  858. continue
  859. # Only the first alias (skipped above) should have None join_type
  860. assert self.alias_map[alias].join_type is not None
  861. parent_alias = self.alias_map[alias].parent_alias
  862. parent_louter = (
  863. parent_alias and self.alias_map[parent_alias].join_type == LOUTER
  864. )
  865. already_louter = self.alias_map[alias].join_type == LOUTER
  866. if (self.alias_map[alias].nullable or parent_louter) and not already_louter:
  867. self.alias_map[alias] = self.alias_map[alias].promote()
  868. # Join type of 'alias' changed, so re-examine all aliases that
  869. # refer to this one.
  870. aliases.extend(
  871. join
  872. for join in self.alias_map
  873. if self.alias_map[join].parent_alias == alias
  874. and join not in aliases
  875. )
  876. def demote_joins(self, aliases):
  877. """
  878. Change join type from LOUTER to INNER for all joins in aliases.
  879. Similarly to promote_joins(), this method must ensure no join chains
  880. containing first an outer, then an inner join are generated. If we
  881. are demoting b->c join in chain a LOUTER b LOUTER c then we must
  882. demote a->b automatically, or otherwise the demotion of b->c doesn't
  883. actually change anything in the query results. .
  884. """
  885. aliases = list(aliases)
  886. while aliases:
  887. alias = aliases.pop(0)
  888. if self.alias_map[alias].join_type == LOUTER:
  889. self.alias_map[alias] = self.alias_map[alias].demote()
  890. parent_alias = self.alias_map[alias].parent_alias
  891. if self.alias_map[parent_alias].join_type == INNER:
  892. aliases.append(parent_alias)
  893. def reset_refcounts(self, to_counts):
  894. """
  895. Reset reference counts for aliases so that they match the value passed
  896. in `to_counts`.
  897. """
  898. for alias, cur_refcount in self.alias_refcount.copy().items():
  899. unref_amount = cur_refcount - to_counts.get(alias, 0)
  900. self.unref_alias(alias, unref_amount)
  901. def change_aliases(self, change_map):
  902. """
  903. Change the aliases in change_map (which maps old-alias -> new-alias),
  904. relabelling any references to them in select columns and the where
  905. clause.
  906. """
  907. if not change_map:
  908. return self
  909. # If keys and values of change_map were to intersect, an alias might be
  910. # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending
  911. # on their order in change_map.
  912. assert set(change_map).isdisjoint(change_map.values())
  913. # 1. Update references in "select" (normal columns plus aliases),
  914. # "group by" and "where".
  915. self.where.relabel_aliases(change_map)
  916. if isinstance(self.group_by, tuple):
  917. self.group_by = tuple(
  918. [col.relabeled_clone(change_map) for col in self.group_by]
  919. )
  920. self.select = tuple([col.relabeled_clone(change_map) for col in self.select])
  921. self.annotations = self.annotations and {
  922. key: col.relabeled_clone(change_map)
  923. for key, col in self.annotations.items()
  924. }
  925. # 2. Rename the alias in the internal table/alias datastructures.
  926. for old_alias, new_alias in change_map.items():
  927. if old_alias not in self.alias_map:
  928. continue
  929. alias_data = self.alias_map[old_alias].relabeled_clone(change_map)
  930. self.alias_map[new_alias] = alias_data
  931. self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
  932. del self.alias_refcount[old_alias]
  933. del self.alias_map[old_alias]
  934. table_aliases = self.table_map[alias_data.table_name]
  935. for pos, alias in enumerate(table_aliases):
  936. if alias == old_alias:
  937. table_aliases[pos] = new_alias
  938. break
  939. # 3. Rename the direct external aliases and the ones of combined
  940. # queries (union, intersection, difference).
  941. self.external_aliases = {
  942. # Table is aliased or it's being changed and thus is aliased.
  943. change_map.get(alias, alias): (aliased or alias in change_map)
  944. for alias, aliased in self.external_aliases.items()
  945. }
  946. for combined_query in self.combined_queries:
  947. external_change_map = {
  948. alias: aliased
  949. for alias, aliased in change_map.items()
  950. if alias in combined_query.external_aliases
  951. }
  952. combined_query.change_aliases(external_change_map)
  953. def bump_prefix(self, other_query, exclude=None):
  954. """
  955. Change the alias prefix to the next letter in the alphabet in a way
  956. that the other query's aliases and this query's aliases will not
  957. conflict. Even tables that previously had no alias will get an alias
  958. after this call. To prevent changing aliases use the exclude parameter.
  959. """
  960. def prefix_gen():
  961. """
  962. Generate a sequence of characters in alphabetical order:
  963. -> 'A', 'B', 'C', ...
  964. When the alphabet is finished, the sequence will continue with the
  965. Cartesian product:
  966. -> 'AA', 'AB', 'AC', ...
  967. """
  968. alphabet = ascii_uppercase
  969. prefix = chr(ord(self.alias_prefix) + 1)
  970. yield prefix
  971. for n in count(1):
  972. seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet
  973. for s in product(seq, repeat=n):
  974. yield "".join(s)
  975. prefix = None
  976. if self.alias_prefix != other_query.alias_prefix:
  977. # No clashes between self and outer query should be possible.
  978. return
  979. # Explicitly avoid infinite loop. The constant divider is based on how
  980. # much depth recursive subquery references add to the stack. This value
  981. # might need to be adjusted when adding or removing function calls from
  982. # the code path in charge of performing these operations.
  983. local_recursion_limit = sys.getrecursionlimit() // 16
  984. for pos, prefix in enumerate(prefix_gen()):
  985. if prefix not in self.subq_aliases:
  986. self.alias_prefix = prefix
  987. break
  988. if pos > local_recursion_limit:
  989. raise RecursionError(
  990. "Maximum recursion depth exceeded: too many subqueries."
  991. )
  992. self.subq_aliases = self.subq_aliases.union([self.alias_prefix])
  993. other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)
  994. if exclude is None:
  995. exclude = {}
  996. self.change_aliases(
  997. {
  998. alias: "%s%d" % (self.alias_prefix, pos)
  999. for pos, alias in enumerate(self.alias_map)
  1000. if alias not in exclude
  1001. }
  1002. )
  1003. def get_initial_alias(self):
  1004. """
  1005. Return the first alias for this query, after increasing its reference
  1006. count.
  1007. """
  1008. if self.alias_map:
  1009. alias = self.base_table
  1010. self.ref_alias(alias)
  1011. elif self.model:
  1012. alias = self.join(self.base_table_class(self.get_meta().db_table, None))
  1013. else:
  1014. alias = None
  1015. return alias
  1016. def count_active_tables(self):
  1017. """
  1018. Return the number of tables in this query with a non-zero reference
  1019. count. After execution, the reference counts are zeroed, so tables
  1020. added in compiler will not be seen by this method.
  1021. """
  1022. return len([1 for count in self.alias_refcount.values() if count])
  1023. def join(self, join, reuse=None):
  1024. """
  1025. Return an alias for the 'join', either reusing an existing alias for
  1026. that join or creating a new one. 'join' is either a base_table_class or
  1027. join_class.
  1028. The 'reuse' parameter can be either None which means all joins are
  1029. reusable, or it can be a set containing the aliases that can be reused.
  1030. A join is always created as LOUTER if the lhs alias is LOUTER to make
  1031. sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new
  1032. joins are created as LOUTER if the join is nullable.
  1033. """
  1034. reuse_aliases = [
  1035. a
  1036. for a, j in self.alias_map.items()
  1037. if (reuse is None or a in reuse) and j == join
  1038. ]
  1039. if reuse_aliases:
  1040. if join.table_alias in reuse_aliases:
  1041. reuse_alias = join.table_alias
  1042. else:
  1043. # Reuse the most recent alias of the joined table
  1044. # (a many-to-many relation may be joined multiple times).
  1045. reuse_alias = reuse_aliases[-1]
  1046. self.ref_alias(reuse_alias)
  1047. return reuse_alias
  1048. # No reuse is possible, so we need a new alias.
  1049. alias, _ = self.table_alias(
  1050. join.table_name, create=True, filtered_relation=join.filtered_relation
  1051. )
  1052. if join.join_type:
  1053. if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:
  1054. join_type = LOUTER
  1055. else:
  1056. join_type = INNER
  1057. join.join_type = join_type
  1058. join.table_alias = alias
  1059. self.alias_map[alias] = join
  1060. if filtered_relation := join.filtered_relation:
  1061. resolve_reuse = reuse
  1062. if resolve_reuse is not None:
  1063. resolve_reuse = set(reuse) | {alias}
  1064. joins_len = len(self.alias_map)
  1065. join.filtered_relation = filtered_relation.resolve_expression(
  1066. self, reuse=resolve_reuse
  1067. )
  1068. # Some joins were during expression resolving, they must be present
  1069. # before the one we just added.
  1070. if joins_len < len(self.alias_map):
  1071. self.alias_map[alias] = self.alias_map.pop(alias)
  1072. return alias
  1073. def join_parent_model(self, opts, model, alias, seen):
  1074. """
  1075. Make sure the given 'model' is joined in the query. If 'model' isn't
  1076. a parent of 'opts' or if it is None this method is a no-op.
  1077. The 'alias' is the root alias for starting the join, 'seen' is a dict
  1078. of model -> alias of existing joins. It must also contain a mapping
  1079. of None -> some alias. This will be returned in the no-op case.
  1080. """
  1081. if model in seen:
  1082. return seen[model]
  1083. chain = opts.get_base_chain(model)
  1084. if not chain:
  1085. return alias
  1086. curr_opts = opts
  1087. for int_model in chain:
  1088. if int_model in seen:
  1089. curr_opts = int_model._meta
  1090. alias = seen[int_model]
  1091. continue
  1092. # Proxy model have elements in base chain
  1093. # with no parents, assign the new options
  1094. # object and skip to the next base in that
  1095. # case
  1096. if not curr_opts.parents[int_model]:
  1097. curr_opts = int_model._meta
  1098. continue
  1099. link_field = curr_opts.get_ancestor_link(int_model)
  1100. join_info = self.setup_joins([link_field.name], curr_opts, alias)
  1101. curr_opts = int_model._meta
  1102. alias = seen[int_model] = join_info.joins[-1]
  1103. return alias or seen[None]
  1104. def check_alias(self, alias):
  1105. # RemovedInDjango70Warning: When the deprecation ends, remove.
  1106. if "%" in alias:
  1107. warnings.warn(
  1108. "Using percent signs in a column alias is deprecated.",
  1109. category=RemovedInDjango70Warning,
  1110. skip_file_prefixes=django_file_prefixes(),
  1111. )
  1112. if FORBIDDEN_ALIAS_PATTERN.search(alias):
  1113. raise ValueError(
  1114. "Column aliases cannot contain whitespace characters, hashes, "
  1115. # RemovedInDjango70Warning: When the deprecation ends, replace
  1116. # with:
  1117. # "control characters, quotation marks, semicolons, percent "
  1118. # "signs, or SQL comments."
  1119. "control characters, quotation marks, semicolons, or SQL comments."
  1120. )
  1121. def add_annotation(self, annotation, alias, select=True):
  1122. """Add a single annotation expression to the Query."""
  1123. self.check_alias(alias)
  1124. annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None)
  1125. if select:
  1126. self.append_annotation_mask([alias])
  1127. else:
  1128. self.set_annotation_mask(set(self.annotation_select).difference({alias}))
  1129. self.annotations[alias] = annotation
  1130. if select and self.selected:
  1131. self.selected[alias] = alias
  1132. @property
  1133. def _subquery_fields_len(self):
  1134. if not self.has_select_fields or not self.select:
  1135. return len(self.model._meta.pk_fields)
  1136. return len(self.select) + sum(
  1137. len(expr.targets) - 1 for expr in self.select if isinstance(expr, ColPairs)
  1138. )
  1139. def resolve_expression(self, query, *args, **kwargs):
  1140. clone = self.clone()
  1141. # Subqueries need to use a different set of aliases than the outer
  1142. # query.
  1143. clone.bump_prefix(query)
  1144. clone.subquery = True
  1145. clone.where.resolve_expression(query, *args, **kwargs)
  1146. # Resolve combined queries.
  1147. if clone.combinator:
  1148. clone.combined_queries = tuple(
  1149. [
  1150. combined_query.resolve_expression(query, *args, **kwargs)
  1151. for combined_query in clone.combined_queries
  1152. ]
  1153. )
  1154. for key, value in clone.annotations.items():
  1155. resolved = value.resolve_expression(query, *args, **kwargs)
  1156. if hasattr(resolved, "external_aliases"):
  1157. resolved.external_aliases.update(clone.external_aliases)
  1158. clone.annotations[key] = resolved
  1159. # Outer query's aliases are considered external.
  1160. for alias, table in query.alias_map.items():
  1161. clone.external_aliases[alias] = (
  1162. isinstance(table, Join)
  1163. and table.join_field.related_model._meta.db_table != alias
  1164. ) or (
  1165. isinstance(table, BaseTable) and table.table_name != table.table_alias
  1166. )
  1167. return clone
  1168. def get_external_cols(self):
  1169. exprs = chain(self.annotations.values(), self.where.children)
  1170. return [
  1171. col
  1172. for col in self._gen_cols(exprs, include_external=True)
  1173. if col.alias in self.external_aliases
  1174. ]
  1175. def get_group_by_cols(self, wrapper=None):
  1176. # If wrapper is referenced by an alias for an explicit GROUP BY through
  1177. # values() a reference to this expression and not the self must be
  1178. # returned to ensure external column references are not grouped against
  1179. # as well.
  1180. external_cols = self.get_external_cols()
  1181. if any(col.possibly_multivalued for col in external_cols):
  1182. return [wrapper or self]
  1183. return external_cols
  1184. def as_sql(self, compiler, connection):
  1185. # Some backends (e.g. Oracle) raise an error when a subquery contains
  1186. # unnecessary ORDER BY clause.
  1187. if (
  1188. self.subquery
  1189. and not connection.features.ignores_unnecessary_order_by_in_subqueries
  1190. ):
  1191. self.clear_ordering(force=False)
  1192. for query in self.combined_queries:
  1193. query.clear_ordering(force=False)
  1194. sql, params = self.get_compiler(connection=connection).as_sql()
  1195. if self.subquery:
  1196. sql = "(%s)" % sql
  1197. return sql, params
  1198. def resolve_lookup_value(self, value, can_reuse, allow_joins, summarize=False):
  1199. if hasattr(value, "resolve_expression"):
  1200. value = value.resolve_expression(
  1201. self,
  1202. reuse=can_reuse,
  1203. allow_joins=allow_joins,
  1204. summarize=summarize,
  1205. )
  1206. elif isinstance(value, (list, tuple)):
  1207. # The items of the iterable may be expressions and therefore need
  1208. # to be resolved independently.
  1209. values = (
  1210. self.resolve_lookup_value(sub_value, can_reuse, allow_joins, summarize)
  1211. for sub_value in value
  1212. )
  1213. type_ = type(value)
  1214. if hasattr(type_, "_make"): # namedtuple
  1215. return type_(*values)
  1216. return type_(values)
  1217. return value
  1218. def solve_lookup_type(self, lookup, summarize=False):
  1219. """
  1220. Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').
  1221. """
  1222. lookup_splitted = lookup.split(LOOKUP_SEP)
  1223. if self.annotations:
  1224. annotation, expression_lookups = refs_expression(
  1225. lookup_splitted, self.annotations
  1226. )
  1227. if annotation:
  1228. expression = self.annotations[annotation]
  1229. if summarize:
  1230. expression = Ref(annotation, expression)
  1231. return expression_lookups, (), expression
  1232. _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  1233. field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]
  1234. if len(lookup_parts) > 1 and not field_parts:
  1235. raise FieldError(
  1236. 'Invalid lookup "%s" for model %s".'
  1237. % (lookup, self.get_meta().model.__name__)
  1238. )
  1239. return lookup_parts, field_parts, False
  1240. def check_query_object_type(self, value, opts, field):
  1241. """
  1242. Check whether the object passed while querying is of the correct type.
  1243. If not, raise a ValueError specifying the wrong object.
  1244. """
  1245. if hasattr(value, "_meta"):
  1246. if not check_rel_lookup_compatibility(value._meta.model, opts, field):
  1247. raise ValueError(
  1248. 'Cannot query "%s": Must be "%s" instance.'
  1249. % (value, opts.object_name)
  1250. )
  1251. def check_related_objects(self, field, value, opts):
  1252. """Check the type of object passed to query relations."""
  1253. if field.is_relation:
  1254. # Check that the field and the queryset use the same model in a
  1255. # query like .filter(author=Author.objects.all()). For example, the
  1256. # opts would be Author's (from the author field) and value.model
  1257. # would be Author.objects.all() queryset's .model (Author also).
  1258. # The field is the related field on the lhs side.
  1259. if (
  1260. isinstance(value, Query)
  1261. and not value.has_select_fields
  1262. and not check_rel_lookup_compatibility(value.model, opts, field)
  1263. ):
  1264. raise ValueError(
  1265. 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".'
  1266. % (value.model._meta.object_name, opts.object_name)
  1267. )
  1268. elif hasattr(value, "_meta"):
  1269. self.check_query_object_type(value, opts, field)
  1270. elif hasattr(value, "__iter__"):
  1271. for v in value:
  1272. self.check_query_object_type(v, opts, field)
  1273. def check_filterable(self, expression):
  1274. """Raise an error if expression cannot be used in a WHERE clause."""
  1275. if hasattr(expression, "resolve_expression") and not getattr(
  1276. expression, "filterable", True
  1277. ):
  1278. raise NotSupportedError(
  1279. expression.__class__.__name__ + " is disallowed in the filter "
  1280. "clause."
  1281. )
  1282. if hasattr(expression, "get_source_expressions"):
  1283. for expr in expression.get_source_expressions():
  1284. self.check_filterable(expr)
  1285. def build_lookup(self, lookups, lhs, rhs):
  1286. """
  1287. Try to extract transforms and lookup from given lhs.
  1288. The lhs value is something that works like SQLExpression.
  1289. The rhs value is what the lookup is going to compare against.
  1290. The lookups is a list of names to extract using get_lookup()
  1291. and get_transform().
  1292. """
  1293. # __exact is the default lookup if one isn't given.
  1294. *transforms, lookup_name = lookups or ["exact"]
  1295. for name in transforms:
  1296. lhs = self.try_transform(lhs, name, lookups)
  1297. # First try get_lookup() so that the lookup takes precedence if the lhs
  1298. # supports both transform and lookup for the name.
  1299. lookup_class = lhs.get_lookup(lookup_name)
  1300. if not lookup_class:
  1301. # A lookup wasn't found. Try to interpret the name as a transform
  1302. # and do an Exact lookup against it.
  1303. lhs = self.try_transform(lhs, lookup_name)
  1304. lookup_name = "exact"
  1305. lookup_class = lhs.get_lookup(lookup_name)
  1306. if not lookup_class:
  1307. return
  1308. lookup = lookup_class(lhs, rhs)
  1309. # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
  1310. # uses of None as a query value unless the lookup supports it.
  1311. if lookup.rhs is None and not lookup.can_use_none_as_rhs:
  1312. if lookup_name not in ("exact", "iexact"):
  1313. raise ValueError("Cannot use None as a query value")
  1314. return lhs.get_lookup("isnull")(lhs, True)
  1315. # For Oracle '' is equivalent to null. The check must be done at this
  1316. # stage because join promotion can't be done in the compiler. Using
  1317. # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.
  1318. # A similar thing is done in is_nullable(), too.
  1319. if (
  1320. lookup_name in ("exact", "iexact")
  1321. and lookup.rhs == ""
  1322. and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls
  1323. ):
  1324. return lhs.get_lookup("isnull")(lhs, True)
  1325. return lookup
  1326. def try_transform(self, lhs, name, lookups=None):
  1327. """
  1328. Helper method for build_lookup(). Try to fetch and initialize
  1329. a transform for name parameter from lhs.
  1330. """
  1331. transform_class = lhs.get_transform(name)
  1332. if transform_class:
  1333. return transform_class(lhs)
  1334. else:
  1335. output_field = lhs.output_field.__class__
  1336. suggested_lookups = difflib.get_close_matches(
  1337. name, lhs.output_field.get_lookups()
  1338. )
  1339. if suggested_lookups:
  1340. suggestion = ", perhaps you meant %s?" % " or ".join(suggested_lookups)
  1341. else:
  1342. suggestion = "."
  1343. if lookups is not None:
  1344. name_index = lookups.index(name)
  1345. unsupported_lookup = LOOKUP_SEP.join(lookups[name_index:])
  1346. else:
  1347. unsupported_lookup = name
  1348. raise FieldError(
  1349. "Unsupported lookup '%s' for %s or join on the field not "
  1350. "permitted%s" % (unsupported_lookup, output_field.__name__, suggestion)
  1351. )
  1352. def build_filter(
  1353. self,
  1354. filter_expr,
  1355. branch_negated=False,
  1356. current_negated=False,
  1357. can_reuse=None,
  1358. allow_joins=True,
  1359. split_subq=True,
  1360. check_filterable=True,
  1361. summarize=False,
  1362. update_join_types=True,
  1363. ):
  1364. """
  1365. Build a WhereNode for a single filter clause but don't add it
  1366. to this Query. Query.add_q() will then add this filter to the where
  1367. Node.
  1368. The 'branch_negated' tells us if the current branch contains any
  1369. negations. This will be used to determine if subqueries are needed.
  1370. The 'current_negated' is used to determine if the current filter is
  1371. negated or not and this will be used to determine if IS NULL filtering
  1372. is needed.
  1373. The difference between current_negated and branch_negated is that
  1374. branch_negated is set on first negation, but current_negated is
  1375. flipped for each negation.
  1376. Note that add_filter will not do any negating itself, that is done
  1377. upper in the code by add_q().
  1378. The 'can_reuse' is a set of reusable joins for multijoins.
  1379. The method will create a filter clause that can be added to the current
  1380. query. However, if the filter isn't added to the query then the caller
  1381. is responsible for unreffing the joins used.
  1382. """
  1383. if isinstance(filter_expr, dict):
  1384. raise FieldError("Cannot parse keyword query as dict")
  1385. if isinstance(filter_expr, Q):
  1386. return self._add_q(
  1387. filter_expr,
  1388. branch_negated=branch_negated,
  1389. current_negated=current_negated,
  1390. used_aliases=can_reuse,
  1391. allow_joins=allow_joins,
  1392. split_subq=split_subq,
  1393. check_filterable=check_filterable,
  1394. summarize=summarize,
  1395. update_join_types=update_join_types,
  1396. )
  1397. if hasattr(filter_expr, "resolve_expression"):
  1398. if not getattr(filter_expr, "conditional", False):
  1399. raise TypeError("Cannot filter against a non-conditional expression.")
  1400. condition = filter_expr.resolve_expression(
  1401. self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize
  1402. )
  1403. if not isinstance(condition, Lookup):
  1404. condition = self.build_lookup(["exact"], condition, True)
  1405. return WhereNode([condition], connector=AND), []
  1406. arg, value = filter_expr
  1407. if not arg:
  1408. raise FieldError("Cannot parse keyword query %r" % arg)
  1409. lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize)
  1410. if check_filterable:
  1411. self.check_filterable(reffed_expression)
  1412. if not allow_joins and len(parts) > 1:
  1413. raise FieldError("Joined field references are not permitted in this query")
  1414. pre_joins = self.alias_refcount.copy()
  1415. value = self.resolve_lookup_value(value, can_reuse, allow_joins, summarize)
  1416. used_joins = {
  1417. k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)
  1418. }
  1419. if check_filterable:
  1420. self.check_filterable(value)
  1421. if reffed_expression:
  1422. condition = self.build_lookup(lookups, reffed_expression, value)
  1423. return WhereNode([condition], connector=AND), []
  1424. opts = self.get_meta()
  1425. alias = self.get_initial_alias()
  1426. allow_many = not branch_negated or not split_subq
  1427. try:
  1428. join_info = self.setup_joins(
  1429. parts,
  1430. opts,
  1431. alias,
  1432. can_reuse=can_reuse,
  1433. allow_many=allow_many,
  1434. )
  1435. # Prevent iterator from being consumed by check_related_objects()
  1436. if isinstance(value, Iterator):
  1437. value = list(value)
  1438. self.check_related_objects(join_info.final_field, value, join_info.opts)
  1439. # split_exclude() needs to know which joins were generated for the
  1440. # lookup parts
  1441. self._lookup_joins = join_info.joins
  1442. except MultiJoin as e:
  1443. return self.split_exclude(filter_expr, can_reuse, e.names_with_path)
  1444. # Update used_joins before trimming since they are reused to determine
  1445. # which joins could be later promoted to INNER.
  1446. used_joins.update(join_info.joins)
  1447. targets, alias, join_list = self.trim_joins(
  1448. join_info.targets, join_info.joins, join_info.path
  1449. )
  1450. if can_reuse is not None:
  1451. can_reuse.update(join_list)
  1452. if join_info.final_field.is_relation:
  1453. if len(targets) == 1:
  1454. col = self._get_col(targets[0], join_info.final_field, alias)
  1455. else:
  1456. col = ColPairs(alias, targets, join_info.targets, join_info.final_field)
  1457. else:
  1458. col = self._get_col(targets[0], join_info.final_field, alias)
  1459. condition = self.build_lookup(lookups, col, value)
  1460. lookup_type = condition.lookup_name
  1461. clause = WhereNode([condition], connector=AND)
  1462. require_outer = (
  1463. lookup_type == "isnull" and condition.rhs is True and not current_negated
  1464. )
  1465. if (
  1466. current_negated
  1467. and (lookup_type != "isnull" or condition.rhs is False)
  1468. and condition.rhs is not None
  1469. ):
  1470. require_outer = True
  1471. if lookup_type != "isnull":
  1472. # The condition added here will be SQL like this:
  1473. # NOT (col IS NOT NULL), where the first NOT is added in
  1474. # upper layers of code. The reason for addition is that if col
  1475. # is null, then col != someval will result in SQL "unknown"
  1476. # which isn't the same as in Python. The Python None handling
  1477. # is wanted, and it can be gotten by
  1478. # (col IS NULL OR col != someval)
  1479. # <=>
  1480. # NOT (col IS NOT NULL AND col = someval).
  1481. if (
  1482. self.is_nullable(targets[0])
  1483. or self.alias_map[join_list[-1]].join_type == LOUTER
  1484. ):
  1485. lookup_class = targets[0].get_lookup("isnull")
  1486. col = self._get_col(targets[0], join_info.targets[0], alias)
  1487. # Use OR + IS NULL when RHS `in` values include None.
  1488. if (
  1489. lookup_type == "in"
  1490. # Check containers (not strings or bytes).
  1491. and isinstance(condition.rhs, Iterable)
  1492. and not isinstance(condition.rhs, (str, bytes))
  1493. and any(v is None for v in condition.rhs)
  1494. ):
  1495. clause.add(lookup_class(col, True), OR)
  1496. else:
  1497. clause.add(lookup_class(col, False), AND)
  1498. # If someval is a nullable column, someval IS NOT NULL is
  1499. # added.
  1500. if isinstance(value, Col) and self.is_nullable(value.target):
  1501. lookup_class = value.target.get_lookup("isnull")
  1502. clause.add(lookup_class(value, False), AND)
  1503. return clause, used_joins if not require_outer else ()
  1504. def add_filter(self, filter_lhs, filter_rhs):
  1505. self.add_q(Q((filter_lhs, filter_rhs)))
  1506. def add_q(self, q_object, reuse_all=False):
  1507. """
  1508. A preprocessor for the internal _add_q(). Responsible for doing final
  1509. join promotion.
  1510. """
  1511. # For join promotion this case is doing an AND for the added q_object
  1512. # and existing conditions. So, any existing inner join forces the join
  1513. # type to remain inner. Existing outer joins can however be demoted.
  1514. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
  1515. # rel_a doesn't produce any rows, then the whole condition must fail.
  1516. # So, demotion is OK.
  1517. existing_inner = {
  1518. a for a in self.alias_map if self.alias_map[a].join_type == INNER
  1519. }
  1520. if reuse_all:
  1521. can_reuse = set(self.alias_map)
  1522. else:
  1523. can_reuse = self.used_aliases
  1524. clause, _ = self._add_q(q_object, can_reuse)
  1525. if clause:
  1526. self.where.add(clause, AND)
  1527. self.demote_joins(existing_inner)
  1528. def build_where(self, filter_expr):
  1529. return self.build_filter(filter_expr, allow_joins=False)[0]
  1530. def clear_where(self):
  1531. self.where = WhereNode()
  1532. def _add_q(
  1533. self,
  1534. q_object,
  1535. used_aliases,
  1536. branch_negated=False,
  1537. current_negated=False,
  1538. allow_joins=True,
  1539. split_subq=True,
  1540. check_filterable=True,
  1541. summarize=False,
  1542. update_join_types=True,
  1543. ):
  1544. """Add a Q-object to the current filter."""
  1545. connector = q_object.connector
  1546. current_negated ^= q_object.negated
  1547. branch_negated = branch_negated or q_object.negated
  1548. target_clause = WhereNode(connector=connector, negated=q_object.negated)
  1549. joinpromoter = JoinPromoter(
  1550. q_object.connector, len(q_object.children), current_negated
  1551. )
  1552. for child in q_object.children:
  1553. child_clause, needed_inner = self.build_filter(
  1554. child,
  1555. can_reuse=used_aliases,
  1556. branch_negated=branch_negated,
  1557. current_negated=current_negated,
  1558. allow_joins=allow_joins,
  1559. split_subq=split_subq,
  1560. check_filterable=check_filterable,
  1561. summarize=summarize,
  1562. update_join_types=update_join_types,
  1563. )
  1564. joinpromoter.add_votes(needed_inner)
  1565. if child_clause:
  1566. target_clause.add(child_clause, connector)
  1567. if update_join_types:
  1568. needed_inner = joinpromoter.update_join_types(self)
  1569. else:
  1570. needed_inner = []
  1571. return target_clause, needed_inner
  1572. def add_filtered_relation(self, filtered_relation, alias):
  1573. if "." in alias:
  1574. raise ValueError(
  1575. "FilteredRelation doesn't support aliases with periods "
  1576. "(got %r)." % alias
  1577. )
  1578. self.check_alias(alias)
  1579. filtered_relation.alias = alias
  1580. relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(
  1581. filtered_relation.relation_name
  1582. )
  1583. if relation_lookup_parts:
  1584. raise ValueError(
  1585. "FilteredRelation's relation_name cannot contain lookups "
  1586. "(got %r)." % filtered_relation.relation_name
  1587. )
  1588. for lookup in get_children_from_q(filtered_relation.condition):
  1589. lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)
  1590. shift = 2 if not lookup_parts else 1
  1591. lookup_field_path = lookup_field_parts[:-shift]
  1592. for idx, lookup_field_part in enumerate(lookup_field_path):
  1593. if len(relation_field_parts) > idx:
  1594. if relation_field_parts[idx] != lookup_field_part:
  1595. raise ValueError(
  1596. "FilteredRelation's condition doesn't support "
  1597. "relations outside the %r (got %r)."
  1598. % (filtered_relation.relation_name, lookup)
  1599. )
  1600. if len(lookup_field_parts) > len(relation_field_parts) + 1:
  1601. raise ValueError(
  1602. "FilteredRelation's condition doesn't support nested "
  1603. "relations deeper than the relation_name (got %r for "
  1604. "%r)." % (lookup, filtered_relation.relation_name)
  1605. )
  1606. filtered_relation = filtered_relation.clone()
  1607. filtered_relation.condition = rename_prefix_from_q(
  1608. filtered_relation.relation_name,
  1609. alias,
  1610. filtered_relation.condition,
  1611. )
  1612. self._filtered_relations[filtered_relation.alias] = filtered_relation
  1613. def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):
  1614. """
  1615. Walk the list of names and turns them into PathInfo tuples. A single
  1616. name in 'names' can generate multiple PathInfos (m2m, for example).
  1617. 'names' is the path of names to travel, 'opts' is the model Options we
  1618. start the name resolving from, 'allow_many' is as for setup_joins().
  1619. If fail_on_missing is set to True, then a name that can't be resolved
  1620. will generate a FieldError.
  1621. Return a list of PathInfo tuples. In addition return the final field
  1622. (the last used join field) and target (which is a field guaranteed to
  1623. contain the same value as the final field). Finally, return those names
  1624. that weren't found (which are likely transforms and the final lookup).
  1625. """
  1626. path, names_with_path = [], []
  1627. for pos, name in enumerate(names):
  1628. cur_names_with_path = (name, [])
  1629. if name == "pk" and opts is not None:
  1630. name = opts.pk.name
  1631. field = None
  1632. filtered_relation = None
  1633. try:
  1634. if opts is None:
  1635. raise FieldDoesNotExist
  1636. field = opts.get_field(name)
  1637. except FieldDoesNotExist:
  1638. if name in self.annotation_select:
  1639. field = self.annotation_select[name].output_field
  1640. elif name in self._filtered_relations and pos == 0:
  1641. filtered_relation = self._filtered_relations[name]
  1642. if LOOKUP_SEP in filtered_relation.relation_name:
  1643. parts = filtered_relation.relation_name.split(LOOKUP_SEP)
  1644. filtered_relation_path, field, _, _ = self.names_to_path(
  1645. parts,
  1646. opts,
  1647. allow_many,
  1648. fail_on_missing,
  1649. )
  1650. path.extend(filtered_relation_path[:-1])
  1651. else:
  1652. field = opts.get_field(filtered_relation.relation_name)
  1653. if field is not None:
  1654. # Fields that contain one-to-many relations with a generic
  1655. # model (like a GenericForeignKey) cannot generate reverse
  1656. # relations and therefore cannot be used for reverse querying.
  1657. if field.is_relation and not field.related_model:
  1658. raise FieldError(
  1659. "Field %r does not generate an automatic reverse "
  1660. "relation and therefore cannot be used for reverse "
  1661. "querying. If it is a GenericForeignKey, consider "
  1662. "adding a GenericRelation." % name
  1663. )
  1664. try:
  1665. model = field.model._meta.concrete_model
  1666. except AttributeError:
  1667. # QuerySet.annotate() may introduce fields that aren't
  1668. # attached to a model.
  1669. model = None
  1670. else:
  1671. # We didn't find the current field, so move position back
  1672. # one step.
  1673. pos -= 1
  1674. if pos == -1 or fail_on_missing:
  1675. available = sorted(
  1676. [
  1677. *get_field_names_from_opts(opts),
  1678. *self.annotations,
  1679. *self._filtered_relations,
  1680. ]
  1681. )
  1682. raise FieldError(
  1683. "Cannot resolve keyword '%s' into field. "
  1684. "Choices are: %s" % (name, ", ".join(available))
  1685. )
  1686. break
  1687. # Check if we need any joins for concrete inheritance cases (the
  1688. # field lives in parent, but we are currently in one of its
  1689. # children)
  1690. if opts is not None and model is not opts.model:
  1691. path_to_parent = opts.get_path_to_parent(model)
  1692. if path_to_parent:
  1693. path.extend(path_to_parent)
  1694. cur_names_with_path[1].extend(path_to_parent)
  1695. opts = path_to_parent[-1].to_opts
  1696. if hasattr(field, "path_infos"):
  1697. if filtered_relation:
  1698. pathinfos = field.get_path_info(filtered_relation)
  1699. else:
  1700. pathinfos = field.path_infos
  1701. if not allow_many:
  1702. for inner_pos, p in enumerate(pathinfos):
  1703. if p.m2m:
  1704. cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])
  1705. names_with_path.append(cur_names_with_path)
  1706. raise MultiJoin(pos + 1, names_with_path)
  1707. last = pathinfos[-1]
  1708. path.extend(pathinfos)
  1709. final_field = last.join_field
  1710. opts = last.to_opts
  1711. targets = last.target_fields
  1712. cur_names_with_path[1].extend(pathinfos)
  1713. names_with_path.append(cur_names_with_path)
  1714. else:
  1715. # Local non-relational field.
  1716. final_field = field
  1717. targets = (field,)
  1718. if fail_on_missing and pos + 1 != len(names):
  1719. raise FieldError(
  1720. "Cannot resolve keyword %r into field. Join on '%s'"
  1721. " not permitted." % (names[pos + 1], name)
  1722. )
  1723. break
  1724. return path, final_field, targets, names[pos + 1 :]
  1725. def setup_joins(
  1726. self,
  1727. names,
  1728. opts,
  1729. alias,
  1730. can_reuse=None,
  1731. allow_many=True,
  1732. ):
  1733. """
  1734. Compute the necessary table joins for the passage through the fields
  1735. given in 'names'. 'opts' is the Options class for the current model
  1736. (which gives the table we are starting from), 'alias' is the alias for
  1737. the table to start the joining from.
  1738. The 'can_reuse' defines the reverse foreign key joins we can reuse. It
  1739. can be None in which case all joins are reusable or a set of aliases
  1740. that can be reused. Note that non-reverse foreign keys are always
  1741. reusable when using setup_joins().
  1742. If 'allow_many' is False, then any reverse foreign key seen will
  1743. generate a MultiJoin exception.
  1744. Return the final field involved in the joins, the target field (used
  1745. for any 'where' constraint), the final 'opts' value, the joins, the
  1746. field path traveled to generate the joins, and a transform function
  1747. that takes a field and alias and is equivalent to
  1748. `field.get_col(alias)` in the simple case but wraps field transforms if
  1749. they were included in names.
  1750. The target field is the field containing the concrete value. Final
  1751. field can be something different, for example foreign key pointing to
  1752. that value. Final field is needed for example in some value
  1753. conversions (convert 'obj' in fk__id=obj to pk val using the foreign
  1754. key field for example).
  1755. """
  1756. joins = [alias]
  1757. # The transform can't be applied yet, as joins must be trimmed later.
  1758. # To avoid making every caller of this method look up transforms
  1759. # directly, compute transforms here and create a partial that converts
  1760. # fields to the appropriate wrapped version.
  1761. def final_transformer(field, alias):
  1762. if not self.alias_cols:
  1763. alias = None
  1764. return field.get_col(alias)
  1765. # Try resolving all the names as fields first. If there's an error,
  1766. # treat trailing names as lookups until a field can be resolved.
  1767. last_field_exception = None
  1768. for pivot in range(len(names), 0, -1):
  1769. try:
  1770. path, final_field, targets, rest = self.names_to_path(
  1771. names[:pivot],
  1772. opts,
  1773. allow_many,
  1774. fail_on_missing=True,
  1775. )
  1776. except FieldError as exc:
  1777. if pivot == 1:
  1778. # The first item cannot be a lookup, so it's safe
  1779. # to raise the field error here.
  1780. raise
  1781. else:
  1782. last_field_exception = exc
  1783. else:
  1784. # The transforms are the remaining items that couldn't be
  1785. # resolved into fields.
  1786. transforms = names[pivot:]
  1787. break
  1788. for name in transforms:
  1789. def transform(field, alias, *, name, previous):
  1790. try:
  1791. wrapped = previous(field, alias)
  1792. return self.try_transform(wrapped, name)
  1793. except FieldError:
  1794. # FieldError is raised if the transform doesn't exist.
  1795. if isinstance(final_field, Field) and last_field_exception:
  1796. raise last_field_exception
  1797. else:
  1798. raise
  1799. final_transformer = functools.partial(
  1800. transform, name=name, previous=final_transformer
  1801. )
  1802. final_transformer.has_transforms = True
  1803. # Then, add the path to the query's joins. Note that we can't trim
  1804. # joins at this stage - we will need the information about join type
  1805. # of the trimmed joins.
  1806. for join in path:
  1807. if join.filtered_relation:
  1808. filtered_relation = join.filtered_relation.clone()
  1809. table_alias = filtered_relation.alias
  1810. else:
  1811. filtered_relation = None
  1812. table_alias = None
  1813. opts = join.to_opts
  1814. if join.direct:
  1815. nullable = self.is_nullable(join.join_field)
  1816. else:
  1817. nullable = True
  1818. connection = self.join_class(
  1819. opts.db_table,
  1820. alias,
  1821. table_alias,
  1822. INNER,
  1823. join.join_field,
  1824. nullable,
  1825. filtered_relation=filtered_relation,
  1826. )
  1827. reuse = can_reuse if join.m2m else None
  1828. alias = self.join(connection, reuse=reuse)
  1829. joins.append(alias)
  1830. if join.filtered_relation and can_reuse is not None:
  1831. can_reuse.add(alias)
  1832. return JoinInfo(final_field, targets, opts, joins, path, final_transformer)
  1833. def trim_joins(self, targets, joins, path):
  1834. """
  1835. The 'target' parameter is the final field being joined to, 'joins'
  1836. is the full list of join aliases. The 'path' contain the PathInfos
  1837. used to create the joins.
  1838. Return the final target field and table alias and the new active
  1839. joins.
  1840. Always trim any direct join if the target column is already in the
  1841. previous table. Can't trim reverse joins as it's unknown if there's
  1842. anything on the other side of the join.
  1843. """
  1844. joins = joins[:]
  1845. for pos, info in enumerate(reversed(path)):
  1846. if len(joins) == 1 or not info.direct:
  1847. break
  1848. if info.filtered_relation:
  1849. break
  1850. join_targets = {t.column for t in info.join_field.foreign_related_fields}
  1851. cur_targets = {t.column for t in targets}
  1852. if not cur_targets.issubset(join_targets):
  1853. break
  1854. targets_dict = {
  1855. r[1].column: r[0]
  1856. for r in info.join_field.related_fields
  1857. if r[1].column in cur_targets
  1858. }
  1859. targets = tuple(targets_dict[t.column] for t in targets)
  1860. self.unref_alias(joins.pop())
  1861. return targets, joins[-1], joins
  1862. @classmethod
  1863. def _gen_cols(cls, exprs, include_external=False, resolve_refs=True):
  1864. for expr in exprs:
  1865. if isinstance(expr, Col):
  1866. yield expr
  1867. elif include_external and callable(
  1868. getattr(expr, "get_external_cols", None)
  1869. ):
  1870. yield from expr.get_external_cols()
  1871. elif hasattr(expr, "get_source_expressions"):
  1872. if not resolve_refs and isinstance(expr, Ref):
  1873. continue
  1874. yield from cls._gen_cols(
  1875. expr.get_source_expressions(),
  1876. include_external=include_external,
  1877. resolve_refs=resolve_refs,
  1878. )
  1879. @classmethod
  1880. def _gen_col_aliases(cls, exprs):
  1881. yield from (expr.alias for expr in cls._gen_cols(exprs))
  1882. def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
  1883. annotation = self.annotations.get(name)
  1884. if annotation is not None:
  1885. if not allow_joins:
  1886. for alias in self._gen_col_aliases([annotation]):
  1887. if isinstance(self.alias_map[alias], Join):
  1888. raise FieldError(
  1889. "Joined field references are not permitted in this query"
  1890. )
  1891. if summarize:
  1892. # Summarize currently means we are doing an aggregate() query
  1893. # which is executed as a wrapped subquery if any of the
  1894. # aggregate() elements reference an existing annotation. In
  1895. # that case we need to return a Ref to the subquery's
  1896. # annotation.
  1897. if name not in self.annotation_select:
  1898. raise FieldError(
  1899. "Cannot aggregate over the '%s' alias. Use annotate() "
  1900. "to promote it." % name
  1901. )
  1902. return Ref(name, self.annotation_select[name])
  1903. else:
  1904. return annotation
  1905. else:
  1906. field_list = name.split(LOOKUP_SEP)
  1907. annotation = self.annotations.get(field_list[0])
  1908. if annotation is not None:
  1909. for transform in field_list[1:]:
  1910. annotation = self.try_transform(annotation, transform)
  1911. return annotation
  1912. join_info = self.setup_joins(
  1913. field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse
  1914. )
  1915. targets, final_alias, join_list = self.trim_joins(
  1916. join_info.targets, join_info.joins, join_info.path
  1917. )
  1918. if not allow_joins and len(join_list) > 1:
  1919. raise FieldError(
  1920. "Joined field references are not permitted in this query"
  1921. )
  1922. if len(targets) > 1:
  1923. raise FieldError(
  1924. "Referencing multicolumn fields with F() objects isn't supported"
  1925. )
  1926. # Verify that the last lookup in name is a field or a transform:
  1927. # transform_function() raises FieldError if not.
  1928. transform = join_info.transform_function(targets[0], final_alias)
  1929. if reuse is not None:
  1930. reuse.update(join_list)
  1931. return transform
  1932. def split_exclude(self, filter_expr, can_reuse, names_with_path):
  1933. """
  1934. When doing an exclude against any kind of N-to-many relation, we need
  1935. to use a subquery. This method constructs the nested query, given the
  1936. original exclude filter (filter_expr) and the portion up to the first
  1937. N-to-many relation field.
  1938. For example, if the origin filter is ~Q(child__name='foo'), filter_expr
  1939. is ('child__name', 'foo') and can_reuse is a set of joins usable for
  1940. filters in the original query.
  1941. We will turn this into equivalent of:
  1942. WHERE NOT EXISTS(
  1943. SELECT 1
  1944. FROM child
  1945. WHERE name = 'foo' AND child.parent_id = parent.id
  1946. LIMIT 1
  1947. )
  1948. """
  1949. # Generate the inner query.
  1950. query = self.__class__(self.model)
  1951. query._filtered_relations = self._filtered_relations
  1952. filter_lhs, filter_rhs = filter_expr
  1953. if isinstance(filter_rhs, OuterRef):
  1954. filter_rhs = OuterRef(filter_rhs)
  1955. elif isinstance(filter_rhs, F):
  1956. filter_rhs = OuterRef(filter_rhs.name)
  1957. query.add_filter(filter_lhs, filter_rhs)
  1958. query.clear_ordering(force=True)
  1959. # Try to have as simple as possible subquery -> trim leading joins from
  1960. # the subquery.
  1961. trimmed_prefix, contains_louter = query.trim_start(names_with_path)
  1962. col = query.select[0]
  1963. select_field = col.target
  1964. alias = col.alias
  1965. if alias in can_reuse:
  1966. pk = select_field.model._meta.pk
  1967. # Need to add a restriction so that outer query's filters are in
  1968. # effect for the subquery, too.
  1969. query.bump_prefix(self)
  1970. lookup_class = select_field.get_lookup("exact")
  1971. # Note that the query.select[0].alias is different from alias
  1972. # due to bump_prefix above.
  1973. lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))
  1974. query.where.add(lookup, AND)
  1975. query.external_aliases[alias] = True
  1976. else:
  1977. lookup_class = select_field.get_lookup("exact")
  1978. lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))
  1979. query.where.add(lookup, AND)
  1980. condition, needed_inner = self.build_filter(Exists(query))
  1981. if contains_louter:
  1982. or_null_condition, _ = self.build_filter(
  1983. ("%s__isnull" % trimmed_prefix, True),
  1984. current_negated=True,
  1985. branch_negated=True,
  1986. can_reuse=can_reuse,
  1987. )
  1988. condition.add(or_null_condition, OR)
  1989. # Note that the end result will be:
  1990. # NOT EXISTS (inner_q) OR outercol IS NULL
  1991. # this might look crazy but due to how NULL works, this seems to be
  1992. # correct. If the IS NULL check is removed, then if outercol
  1993. # IS NULL we will not match the row.
  1994. return condition, needed_inner
  1995. def set_empty(self):
  1996. self.where.add(NothingNode(), AND)
  1997. for query in self.combined_queries:
  1998. query.set_empty()
  1999. def is_empty(self):
  2000. return any(isinstance(c, NothingNode) for c in self.where.children)
  2001. def set_limits(self, low=None, high=None):
  2002. """
  2003. Adjust the limits on the rows retrieved. Use low/high to set these,
  2004. as it makes it more Pythonic to read and write. When the SQL query is
  2005. created, convert them to the appropriate offset and limit values.
  2006. Apply any limits passed in here to the existing constraints. Add low
  2007. to the current low value and clamp both to any existing high value.
  2008. """
  2009. if high is not None:
  2010. if self.high_mark is not None:
  2011. self.high_mark = min(self.high_mark, self.low_mark + high)
  2012. else:
  2013. self.high_mark = self.low_mark + high
  2014. if low is not None:
  2015. if self.high_mark is not None:
  2016. self.low_mark = min(self.high_mark, self.low_mark + low)
  2017. else:
  2018. self.low_mark = self.low_mark + low
  2019. if self.low_mark == self.high_mark:
  2020. self.set_empty()
  2021. def clear_limits(self):
  2022. """Clear any existing limits."""
  2023. self.low_mark, self.high_mark = 0, None
  2024. @property
  2025. def is_sliced(self):
  2026. return self.low_mark != 0 or self.high_mark is not None
  2027. def has_limit_one(self):
  2028. return self.high_mark is not None and (self.high_mark - self.low_mark) == 1
  2029. def can_filter(self):
  2030. """
  2031. Return True if adding filters to this instance is still possible.
  2032. Typically, this means no limits or offsets have been put on the
  2033. results.
  2034. """
  2035. return not self.is_sliced
  2036. def clear_select_clause(self):
  2037. """Remove all fields from SELECT clause."""
  2038. self.select = ()
  2039. self.default_cols = False
  2040. self.select_related = False
  2041. self.set_extra_mask(())
  2042. self.set_annotation_mask(())
  2043. self.selected = None
  2044. def clear_select_fields(self):
  2045. """
  2046. Clear the list of fields to select (but not extra_select columns).
  2047. Some queryset types completely replace any existing list of select
  2048. columns.
  2049. """
  2050. self.select = ()
  2051. self.values_select = ()
  2052. self.selected = None
  2053. def add_select_col(self, col, name):
  2054. self.select += (col,)
  2055. self.values_select += (name,)
  2056. self.selected[name] = len(self.select) - 1
  2057. def set_select(self, cols):
  2058. self.default_cols = False
  2059. self.select = tuple(cols)
  2060. def add_distinct_fields(self, *field_names):
  2061. """
  2062. Add and resolve the given fields to the query's "distinct on" clause.
  2063. """
  2064. self.distinct_fields = field_names
  2065. self.distinct = True
  2066. def add_fields(self, field_names, allow_m2m=True):
  2067. """
  2068. Add the given (model) fields to the select set. Add the field names in
  2069. the order specified.
  2070. """
  2071. alias = self.get_initial_alias()
  2072. opts = self.get_meta()
  2073. try:
  2074. cols = []
  2075. for name in field_names:
  2076. # Join promotion note - we must not remove any rows here, so
  2077. # if there is no existing joins, use outer join.
  2078. join_info = self.setup_joins(
  2079. name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m
  2080. )
  2081. targets, final_alias, joins = self.trim_joins(
  2082. join_info.targets,
  2083. join_info.joins,
  2084. join_info.path,
  2085. )
  2086. if len(targets) > 1:
  2087. transformed_targets = [
  2088. join_info.transform_function(target, final_alias)
  2089. for target in targets
  2090. ]
  2091. cols.append(
  2092. ColPairs(
  2093. final_alias if self.alias_cols else None,
  2094. [col.target for col in transformed_targets],
  2095. [col.output_field for col in transformed_targets],
  2096. join_info.final_field,
  2097. )
  2098. )
  2099. else:
  2100. cols.append(join_info.transform_function(targets[0], final_alias))
  2101. if cols:
  2102. self.set_select(cols)
  2103. except MultiJoin:
  2104. raise FieldError("Invalid field name: '%s'" % name)
  2105. except FieldError:
  2106. if LOOKUP_SEP in name:
  2107. # For lookups spanning over relationships, show the error
  2108. # from the model on which the lookup failed.
  2109. raise
  2110. else:
  2111. names = sorted(
  2112. [
  2113. *get_field_names_from_opts(opts),
  2114. *self.extra,
  2115. *self.annotation_select,
  2116. *self._filtered_relations,
  2117. ]
  2118. )
  2119. raise FieldError(
  2120. "Cannot resolve keyword %r into field. "
  2121. "Choices are: %s" % (name, ", ".join(names))
  2122. )
  2123. def add_ordering(self, *ordering):
  2124. """
  2125. Add items from the 'ordering' sequence to the query's "order by"
  2126. clause. These items are either field names (not column names) --
  2127. possibly with a direction prefix ('-' or '?') -- or OrderBy
  2128. expressions.
  2129. If 'ordering' is empty, clear all ordering from the query.
  2130. """
  2131. errors = []
  2132. for item in ordering:
  2133. if isinstance(item, str):
  2134. if item == "?":
  2135. continue
  2136. item = item.removeprefix("-")
  2137. if item in self.annotations:
  2138. continue
  2139. if self.extra and item in self.extra:
  2140. continue
  2141. # names_to_path() validates the lookup. A descriptive
  2142. # FieldError will be raise if it's not.
  2143. self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)
  2144. elif not hasattr(item, "resolve_expression"):
  2145. errors.append(item)
  2146. if getattr(item, "contains_aggregate", False):
  2147. raise FieldError(
  2148. "Using an aggregate in order_by() without also including "
  2149. "it in annotate() is not allowed: %s" % item
  2150. )
  2151. if errors:
  2152. raise FieldError("Invalid order_by arguments: %s" % errors)
  2153. if ordering:
  2154. self.order_by += ordering
  2155. else:
  2156. self.default_ordering = False
  2157. @property
  2158. def orderby_issubset_groupby(self):
  2159. if self.extra_order_by:
  2160. # Raw SQL from extra(order_by=...) can't be reliably compared
  2161. # against resolved OrderBy/Col expressions. Treat as not a subset.
  2162. return False
  2163. if self.group_by in (None, True):
  2164. # There is either no aggregation at all (None), or the group by
  2165. # is generated automatically from model fields (True), in which
  2166. # case the order by is necessarily a subset of them.
  2167. return True
  2168. if not self.order_by:
  2169. # Although an empty set is always a subset, there's no point in
  2170. # clearing ordering when there isn't any. Avoid the clone() below.
  2171. return True
  2172. # Don't pollute the original query (might disrupt joins).
  2173. q = self.clone()
  2174. order_by_set = set()
  2175. for order_by in q.order_by:
  2176. if hasattr(order_by, "resolve_expression"):
  2177. order_by_set.add(order_by.resolve_expression(q))
  2178. elif order_by == "?":
  2179. # Random ordering can't be compared against group by.
  2180. return False
  2181. else:
  2182. order_by_set.add(F(order_by.removeprefix("-")).resolve_expression(q))
  2183. return order_by_set.issubset(self.group_by)
  2184. def clear_ordering(self, force=False, clear_default=True):
  2185. """
  2186. Remove any ordering settings if the current query allows it without
  2187. side effects, set 'force' to True to clear the ordering regardless.
  2188. If 'clear_default' is True, there will be no ordering in the resulting
  2189. query (not even the model's default).
  2190. """
  2191. if not force and (
  2192. self.is_sliced or self.distinct_fields or self.select_for_update
  2193. ):
  2194. return
  2195. self.order_by = ()
  2196. self.extra_order_by = ()
  2197. if clear_default:
  2198. self.default_ordering = False
  2199. # Ordering is cleared on combined queries with clear_default=False
  2200. # when union() and analogues are called, so percolate any possible
  2201. # clear_default=True.
  2202. for query in self.combined_queries:
  2203. query.clear_ordering(force=False, clear_default=clear_default)
  2204. def set_group_by(self, allow_aliases=True):
  2205. """
  2206. Expand the GROUP BY clause required by the query.
  2207. This will usually be the set of all non-aggregate fields in the
  2208. return data. If the database backend supports grouping by the
  2209. primary key, and the query would be equivalent, the optimization
  2210. will be made automatically.
  2211. """
  2212. if allow_aliases and self.values_select:
  2213. # If grouping by aliases is allowed assign selected value aliases
  2214. # by moving them to annotations.
  2215. group_by_annotations = {}
  2216. values_select = {}
  2217. for alias, expr in zip(self.values_select, self.select):
  2218. if isinstance(expr, Col):
  2219. values_select[alias] = expr
  2220. else:
  2221. group_by_annotations[alias] = expr
  2222. self.annotations = {**group_by_annotations, **self.annotations}
  2223. self.append_annotation_mask(group_by_annotations)
  2224. self.select = tuple(values_select.values())
  2225. self.values_select = tuple(values_select)
  2226. if self.selected is not None:
  2227. for index, value_select in enumerate(values_select):
  2228. self.selected[value_select] = index
  2229. group_by = list(self.select)
  2230. for alias, annotation in self.annotation_select.items():
  2231. if not (group_by_cols := annotation.get_group_by_cols()):
  2232. continue
  2233. if allow_aliases and not annotation.contains_aggregate:
  2234. group_by.append(Ref(alias, annotation))
  2235. else:
  2236. group_by.extend(group_by_cols)
  2237. self.group_by = tuple(group_by)
  2238. def add_select_related(self, fields):
  2239. """
  2240. Set up the select_related data structure so that we only select
  2241. certain related models (as opposed to all models, when
  2242. self.select_related=True).
  2243. """
  2244. if isinstance(self.select_related, bool):
  2245. field_dict = {}
  2246. else:
  2247. field_dict = self.select_related
  2248. for field in fields:
  2249. d = field_dict
  2250. for part in field.split(LOOKUP_SEP):
  2251. d = d.setdefault(part, {})
  2252. self.select_related = field_dict
  2253. def add_extra(self, select, select_params, where, params, tables, order_by):
  2254. """
  2255. Add data to the various extra_* attributes for user-created additions
  2256. to the query.
  2257. """
  2258. if select:
  2259. # We need to pair any placeholder markers in the 'select'
  2260. # dictionary with their parameters in 'select_params' so that
  2261. # subsequent updates to the select dictionary also adjust the
  2262. # parameters appropriately.
  2263. select_pairs = {}
  2264. if select_params:
  2265. param_iter = iter(select_params)
  2266. else:
  2267. param_iter = iter([])
  2268. for name, entry in select.items():
  2269. self.check_alias(name)
  2270. entry = str(entry)
  2271. entry_params = []
  2272. pos = entry.find("%s")
  2273. while pos != -1:
  2274. if pos == 0 or entry[pos - 1] != "%":
  2275. entry_params.append(next(param_iter))
  2276. pos = entry.find("%s", pos + 2)
  2277. select_pairs[name] = (entry, entry_params)
  2278. self.extra.update(select_pairs)
  2279. if where or params:
  2280. self.where.add(ExtraWhere(where, params), AND)
  2281. if tables:
  2282. self.extra_tables += tuple(tables)
  2283. if order_by:
  2284. self.extra_order_by = order_by
  2285. def clear_deferred_loading(self):
  2286. """Remove any fields from the deferred loading set."""
  2287. self.deferred_loading = (frozenset(), True)
  2288. def add_deferred_loading(self, field_names):
  2289. """
  2290. Add the given list of model field names to the set of fields to
  2291. exclude from loading from the database when automatic column selection
  2292. is done. Add the new field names to any existing field names that
  2293. are deferred (or removed from any existing field names that are marked
  2294. as the only ones for immediate loading).
  2295. """
  2296. # Fields on related models are stored in the literal double-underscore
  2297. # format, so that we can use a set datastructure. We do the foo__bar
  2298. # splitting and handling when computing the SQL column names (as part
  2299. # of get_columns()).
  2300. existing, defer = self.deferred_loading
  2301. if defer:
  2302. # Add to existing deferred names.
  2303. self.deferred_loading = existing.union(field_names), True
  2304. else:
  2305. # Remove names from the set of any existing "immediate load" names.
  2306. if new_existing := existing.difference(field_names):
  2307. self.deferred_loading = new_existing, False
  2308. else:
  2309. self.clear_deferred_loading()
  2310. if new_only := set(field_names).difference(existing):
  2311. self.deferred_loading = new_only, True
  2312. def add_immediate_loading(self, field_names):
  2313. """
  2314. Add the given list of model field names to the set of fields to
  2315. retrieve when the SQL is executed ("immediate loading" fields). The
  2316. field names replace any existing immediate loading field names. If
  2317. there are field names already specified for deferred loading, remove
  2318. those names from the new field_names before storing the new names
  2319. for immediate loading. (That is, immediate loading overrides any
  2320. existing immediate values, but respects existing deferrals.)
  2321. """
  2322. existing, defer = self.deferred_loading
  2323. field_names = set(field_names)
  2324. if "pk" in field_names:
  2325. field_names.remove("pk")
  2326. field_names.add(self.get_meta().pk.name)
  2327. if defer:
  2328. # Remove any existing deferred names from the current set before
  2329. # setting the new names.
  2330. self.deferred_loading = field_names.difference(existing), False
  2331. else:
  2332. # Replace any existing "immediate load" field names.
  2333. self.deferred_loading = frozenset(field_names), False
  2334. def set_annotation_mask(self, names):
  2335. """Set the mask of annotations that will be returned by the SELECT."""
  2336. if names is None:
  2337. self.annotation_select_mask = None
  2338. else:
  2339. self.annotation_select_mask = set(names)
  2340. if self.selected:
  2341. # Prune the masked annotations.
  2342. self.selected = {
  2343. key: value
  2344. for key, value in self.selected.items()
  2345. if not isinstance(value, str)
  2346. or value in self.annotation_select_mask
  2347. }
  2348. # Append the unmasked annotations.
  2349. for name in names:
  2350. self.selected[name] = name
  2351. self._annotation_select_cache = None
  2352. def append_annotation_mask(self, names):
  2353. if self.annotation_select_mask is not None:
  2354. self.set_annotation_mask(self.annotation_select_mask.union(names))
  2355. def set_extra_mask(self, names):
  2356. """
  2357. Set the mask of extra select items that will be returned by SELECT.
  2358. Don't remove them from the Query since they might be used later.
  2359. """
  2360. if names is None:
  2361. self.extra_select_mask = None
  2362. else:
  2363. self.extra_select_mask = set(names)
  2364. self._extra_select_cache = None
  2365. @property
  2366. def has_select_fields(self):
  2367. return self.selected is not None
  2368. def set_values(self, fields):
  2369. self.select_related = False
  2370. self.clear_deferred_loading()
  2371. self.clear_select_fields()
  2372. selected = {}
  2373. if fields:
  2374. for field in fields:
  2375. self.check_alias(field)
  2376. field_names = []
  2377. extra_names = []
  2378. annotation_names = []
  2379. if not self.extra and not self.annotations:
  2380. # Shortcut - if there are no extra or annotations, then
  2381. # the values() clause must be just field names.
  2382. field_names = list(fields)
  2383. selected = dict(zip(fields, range(len(fields))))
  2384. else:
  2385. self.default_cols = False
  2386. for f in fields:
  2387. if extra := self.extra_select.get(f):
  2388. extra_names.append(f)
  2389. selected[f] = RawSQL(*extra)
  2390. elif f in self.annotation_select:
  2391. annotation_names.append(f)
  2392. selected[f] = f
  2393. elif f in self.annotations:
  2394. if self.annotation_select:
  2395. raise FieldError(
  2396. f"Cannot select the '{f}' alias. It was excluded "
  2397. f"by a previous values() or values_list() call. "
  2398. f"Include '{f}' in that call to select it."
  2399. )
  2400. else:
  2401. raise FieldError(
  2402. f"Cannot select the '{f}' alias. Use annotate() "
  2403. f"to promote it."
  2404. )
  2405. else:
  2406. # Call `names_to_path` to ensure a FieldError including
  2407. # annotations about to be masked as valid choices if
  2408. # `f` is not resolvable.
  2409. if self.annotation_select:
  2410. self.names_to_path(f.split(LOOKUP_SEP), self.model._meta)
  2411. selected[f] = len(field_names)
  2412. field_names.append(f)
  2413. self.set_extra_mask(extra_names)
  2414. self.set_annotation_mask(annotation_names)
  2415. else:
  2416. field_names = [f.attname for f in self.model._meta.concrete_fields]
  2417. selected = dict.fromkeys(field_names, None)
  2418. # Selected annotations must be known before setting the GROUP BY
  2419. # clause.
  2420. if self.group_by is True:
  2421. self.add_fields(
  2422. (f.attname for f in self.model._meta.concrete_fields), False
  2423. )
  2424. # Disable GROUP BY aliases to avoid orphaning references to the
  2425. # SELECT clause which is about to be cleared.
  2426. self.set_group_by(allow_aliases=False)
  2427. self.clear_select_fields()
  2428. elif self.group_by:
  2429. # Resolve GROUP BY annotation references if they are not part of
  2430. # the selected fields anymore.
  2431. group_by = []
  2432. for expr in self.group_by:
  2433. if isinstance(expr, Ref) and expr.refs not in selected:
  2434. expr = self.annotations[expr.refs]
  2435. group_by.append(expr)
  2436. self.group_by = tuple(group_by)
  2437. self.values_select = tuple(field_names)
  2438. self.add_fields(field_names, True)
  2439. self.selected = selected if fields else None
  2440. @property
  2441. def annotation_select(self):
  2442. """
  2443. Return the dictionary of aggregate columns that are not masked and
  2444. should be used in the SELECT clause. Cache this result for performance.
  2445. """
  2446. if self._annotation_select_cache is not None:
  2447. return self._annotation_select_cache
  2448. elif not self.annotations:
  2449. return {}
  2450. elif self.annotation_select_mask is not None:
  2451. self._annotation_select_cache = {
  2452. k: v
  2453. for k, v in self.annotations.items()
  2454. if k in self.annotation_select_mask
  2455. }
  2456. return self._annotation_select_cache
  2457. else:
  2458. return self.annotations
  2459. @property
  2460. def extra_select(self):
  2461. if self._extra_select_cache is not None:
  2462. return self._extra_select_cache
  2463. if not self.extra:
  2464. return {}
  2465. elif self.extra_select_mask is not None:
  2466. self._extra_select_cache = {
  2467. k: v for k, v in self.extra.items() if k in self.extra_select_mask
  2468. }
  2469. return self._extra_select_cache
  2470. else:
  2471. return self.extra
  2472. def trim_start(self, names_with_path):
  2473. """
  2474. Trim joins from the start of the join path. The candidates for trim
  2475. are the PathInfos in names_with_path structure that are m2m joins.
  2476. Also set the select column so the start matches the join.
  2477. This method is meant to be used for generating the subquery joins &
  2478. cols in split_exclude().
  2479. Return a lookup usable for doing outerq.filter(lookup=self) and a
  2480. boolean indicating if the joins in the prefix contain a LEFT OUTER
  2481. join.
  2482. """
  2483. all_paths = []
  2484. for _, paths in names_with_path:
  2485. all_paths.extend(paths)
  2486. contains_louter = False
  2487. # Trim and operate only on tables that were generated for
  2488. # the lookup part of the query. That is, avoid trimming
  2489. # joins generated for F() expressions.
  2490. lookup_tables = [
  2491. t for t in self.alias_map if t in self._lookup_joins or t == self.base_table
  2492. ]
  2493. for trimmed_paths, path in enumerate(all_paths):
  2494. if path.m2m:
  2495. break
  2496. if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:
  2497. contains_louter = True
  2498. alias = lookup_tables[trimmed_paths]
  2499. self.unref_alias(alias)
  2500. # The path.join_field is a Rel, lets get the other side's field
  2501. join_field = path.join_field.field
  2502. # Build the filter prefix.
  2503. paths_in_prefix = trimmed_paths
  2504. trimmed_prefix = []
  2505. for name, path in names_with_path:
  2506. if paths_in_prefix - len(path) < 0:
  2507. break
  2508. trimmed_prefix.append(name)
  2509. paths_in_prefix -= len(path)
  2510. trimmed_prefix.append(join_field.foreign_related_fields[0].name)
  2511. trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)
  2512. # Lets still see if we can trim the first join from the inner query
  2513. # (that is, self). We can't do this for:
  2514. # - LEFT JOINs because we would miss those rows that have nothing on
  2515. # the outer side,
  2516. # - INNER JOINs from filtered relations because we would miss their
  2517. # filters.
  2518. first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]
  2519. if first_join.join_type != LOUTER and not first_join.filtered_relation:
  2520. select_fields = [r[0] for r in join_field.related_fields]
  2521. select_alias = lookup_tables[trimmed_paths + 1]
  2522. self.unref_alias(lookup_tables[trimmed_paths])
  2523. extra_restriction = join_field.get_extra_restriction(
  2524. None, lookup_tables[trimmed_paths + 1]
  2525. )
  2526. if extra_restriction:
  2527. self.where.add(extra_restriction, AND)
  2528. else:
  2529. # TODO: It might be possible to trim more joins from the start of
  2530. # the inner query if it happens to have a longer join chain
  2531. # containing the values in select_fields. Lets punt this one for
  2532. # now.
  2533. select_fields = [r[1] for r in join_field.related_fields]
  2534. select_alias = lookup_tables[trimmed_paths]
  2535. # The found starting point is likely a join_class instead of a
  2536. # base_table_class reference. But the first entry in the query's FROM
  2537. # clause must not be a JOIN.
  2538. for table in self.alias_map:
  2539. if self.alias_refcount[table] > 0:
  2540. self.alias_map[table] = self.base_table_class(
  2541. self.alias_map[table].table_name,
  2542. table,
  2543. )
  2544. break
  2545. self.set_select([f.get_col(select_alias) for f in select_fields])
  2546. return trimmed_prefix, contains_louter
  2547. def is_nullable(self, field):
  2548. """
  2549. Check if the given field should be treated as nullable.
  2550. Some backends treat '' as null and Django treats such fields as
  2551. nullable for those backends. In such situations field.null can be
  2552. False even if we should treat the field as nullable.
  2553. """
  2554. # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
  2555. # (nor should it have) knowledge of which connection is going to be
  2556. # used. The proper fix would be to defer all decisions where
  2557. # is_nullable() is needed to the compiler stage, but that is not easy
  2558. # to do currently.
  2559. return field.null or (
  2560. field.empty_strings_allowed
  2561. and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls
  2562. )
  2563. def get_order_dir(field, default="ASC"):
  2564. """
  2565. Return the field name and direction for an order specification. For
  2566. example, '-foo' is returned as ('foo', 'DESC').
  2567. The 'default' param is used to indicate which way no prefix (or a '+'
  2568. prefix) should sort. The '-' prefix always sorts the opposite way.
  2569. """
  2570. dirn = ORDER_DIR[default]
  2571. if field[0] == "-":
  2572. return field[1:], dirn[1]
  2573. return field, dirn[0]
  2574. class JoinPromoter:
  2575. """
  2576. A class to abstract away join promotion problems for complex filter
  2577. conditions.
  2578. """
  2579. def __init__(self, connector, num_children, negated):
  2580. self.connector = connector
  2581. self.negated = negated
  2582. if self.negated:
  2583. if connector == AND:
  2584. self.effective_connector = OR
  2585. else:
  2586. self.effective_connector = AND
  2587. else:
  2588. self.effective_connector = self.connector
  2589. self.num_children = num_children
  2590. # Maps of table alias to how many times it is seen as required for
  2591. # inner and/or outer joins.
  2592. self.votes = Counter()
  2593. def __repr__(self):
  2594. return (
  2595. f"{self.__class__.__qualname__}(connector={self.connector!r}, "
  2596. f"num_children={self.num_children!r}, negated={self.negated!r})"
  2597. )
  2598. def add_votes(self, votes):
  2599. """
  2600. Add single vote per item to self.votes. Parameter can be any
  2601. iterable.
  2602. """
  2603. self.votes.update(votes)
  2604. def update_join_types(self, query):
  2605. """
  2606. Change join types so that the generated query is as efficient as
  2607. possible, but still correct. So, change as many joins as possible
  2608. to INNER, but don't make OUTER joins INNER if that could remove
  2609. results from the query.
  2610. """
  2611. to_promote = set()
  2612. to_demote = set()
  2613. # The effective_connector is used so that NOT (a AND b) is treated
  2614. # similarly to (a OR b) for join promotion.
  2615. for table, votes in self.votes.items():
  2616. # We must use outer joins in OR case when the join isn't contained
  2617. # in all of the joins. Otherwise the INNER JOIN itself could remove
  2618. # valid results. Consider the case where a model with rel_a and
  2619. # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now,
  2620. # if rel_a join doesn't produce any results is null (for example
  2621. # reverse foreign key or null value in direct foreign key), and
  2622. # there is a matching row in rel_b with col=2, then an INNER join
  2623. # to rel_a would remove a valid match from the query. So, we need
  2624. # to promote any existing INNER to LOUTER (it is possible this
  2625. # promotion in turn will be demoted later on).
  2626. if self.effective_connector == OR and votes < self.num_children:
  2627. to_promote.add(table)
  2628. # If connector is AND and there is a filter that can match only
  2629. # when there is a joinable row, then use INNER. For example, in
  2630. # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL
  2631. # as join output, then the col=1 or col=2 can't match (as
  2632. # NULL=anything is always false).
  2633. # For the OR case, if all children voted for a join to be inner,
  2634. # then we can use INNER for the join. For example:
  2635. # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell)
  2636. # then if rel_a doesn't produce any rows, the whole condition
  2637. # can't match. Hence we can safely use INNER join.
  2638. if self.effective_connector == AND or (
  2639. self.effective_connector == OR and votes == self.num_children
  2640. ):
  2641. to_demote.add(table)
  2642. # Finally, what happens in cases where we have:
  2643. # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0
  2644. # Now, we first generate the OR clause, and promote joins for it
  2645. # in the first if branch above. Both rel_a and rel_b are promoted
  2646. # to LOUTER joins. After that we do the AND case. The OR case
  2647. # voted no inner joins but the rel_a__col__gte=0 votes inner join
  2648. # for rel_a. We demote it back to INNER join (in AND case a single
  2649. # vote is enough). The demotion is OK, if rel_a doesn't produce
  2650. # rows, then the rel_a__col__gte=0 clause can't be true, and thus
  2651. # the whole clause must be false. So, it is safe to use INNER
  2652. # join.
  2653. # Note that in this example we could just as well have the __gte
  2654. # clause and the OR clause swapped. Or we could replace the __gte
  2655. # clause with an OR clause containing rel_a__col=1|rel_a__col=2,
  2656. # and again we could safely demote to INNER.
  2657. query.promote_joins(to_promote)
  2658. query.demote_joins(to_demote)
  2659. return to_demote