query.py 116 KB

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