query.py 113 KB

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