query.py 113 KB

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