query.py 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098
  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. from collections import OrderedDict
  9. import copy
  10. import warnings
  11. from django.core.exceptions import FieldError
  12. from django.db import connections, DEFAULT_DB_ALIAS
  13. from django.db.models.constants import LOOKUP_SEP
  14. from django.db.models.aggregates import refs_aggregate
  15. from django.db.models.expressions import ExpressionNode
  16. from django.db.models.fields import FieldDoesNotExist
  17. from django.db.models.query_utils import Q
  18. from django.db.models.related import PathInfo
  19. from django.db.models.sql import aggregates as base_aggregates_module
  20. from django.db.models.sql.constants import (QUERY_TERMS, ORDER_DIR, SINGLE,
  21. ORDER_PATTERN, JoinInfo, SelectInfo)
  22. from django.db.models.sql.datastructures import EmptyResultSet, Empty, MultiJoin, Col
  23. from django.db.models.sql.expressions import SQLEvaluator
  24. from django.db.models.sql.where import (WhereNode, Constraint, EverythingNode,
  25. ExtraWhere, AND, OR, EmptyWhere)
  26. from django.utils import six
  27. from django.utils.deprecation import RemovedInDjango19Warning
  28. from django.utils.encoding import force_text
  29. from django.utils.tree import Node
  30. __all__ = ['Query', 'RawQuery']
  31. class RawQuery(object):
  32. """
  33. A single raw SQL query
  34. """
  35. def __init__(self, sql, using, params=None):
  36. self.params = params or ()
  37. self.sql = sql
  38. self.using = using
  39. self.cursor = None
  40. # Mirror some properties of a normal query so that
  41. # the compiler can be used to process results.
  42. self.low_mark, self.high_mark = 0, None # Used for offset/limit
  43. self.extra_select = {}
  44. self.aggregate_select = {}
  45. def clone(self, using):
  46. return RawQuery(self.sql, using, params=self.params)
  47. def convert_values(self, value, field, connection):
  48. """Convert the database-returned value into a type that is consistent
  49. across database backends.
  50. By default, this defers to the underlying backend operations, but
  51. it can be overridden by Query classes for specific backends.
  52. """
  53. return connection.ops.convert_values(value, field)
  54. def get_columns(self):
  55. if self.cursor is None:
  56. self._execute_query()
  57. converter = connections[self.using].introspection.table_name_converter
  58. return [converter(column_meta[0])
  59. for column_meta in self.cursor.description]
  60. def __iter__(self):
  61. # Always execute a new query for a new iterator.
  62. # This could be optimized with a cache at the expense of RAM.
  63. self._execute_query()
  64. if not connections[self.using].features.can_use_chunked_reads:
  65. # If the database can't use chunked reads we need to make sure we
  66. # evaluate the entire query up front.
  67. result = list(self.cursor)
  68. else:
  69. result = self.cursor
  70. return iter(result)
  71. def __repr__(self):
  72. return "<RawQuery: %r>" % (self.sql % tuple(self.params))
  73. def _execute_query(self):
  74. self.cursor = connections[self.using].cursor()
  75. self.cursor.execute(self.sql, self.params)
  76. class Query(object):
  77. """
  78. A single SQL query.
  79. """
  80. # SQL join types. These are part of the class because their string forms
  81. # vary from database to database and can be customised by a subclass.
  82. INNER = 'INNER JOIN'
  83. LOUTER = 'LEFT OUTER JOIN'
  84. alias_prefix = 'T'
  85. subq_aliases = frozenset([alias_prefix])
  86. query_terms = QUERY_TERMS
  87. aggregates_module = base_aggregates_module
  88. compiler = 'SQLCompiler'
  89. def __init__(self, model, where=WhereNode):
  90. self.model = model
  91. self.alias_refcount = {}
  92. # alias_map is the most important data structure regarding joins.
  93. # It's used for recording which joins exist in the query and what
  94. # type they are. The key is the alias of the joined table (possibly
  95. # the table name) and the value is JoinInfo from constants.py.
  96. self.alias_map = {}
  97. self.table_map = {} # Maps table names to list of aliases.
  98. self.join_map = {}
  99. self.default_cols = True
  100. self.default_ordering = True
  101. self.standard_ordering = True
  102. self.used_aliases = set()
  103. self.filter_is_sticky = False
  104. self.included_inherited_models = {}
  105. # SQL-related attributes
  106. # Select and related select clauses as SelectInfo instances.
  107. # The select is used for cases where we want to set up the select
  108. # clause to contain other than default fields (values(), annotate(),
  109. # subqueries...)
  110. self.select = []
  111. # The related_select_cols is used for columns needed for
  112. # select_related - this is populated in the compile stage.
  113. self.related_select_cols = []
  114. self.tables = [] # Aliases in the order they are created.
  115. self.where = where()
  116. self.where_class = where
  117. self.group_by = None
  118. self.having = where()
  119. self.order_by = []
  120. self.low_mark, self.high_mark = 0, None # Used for offset/limit
  121. self.distinct = False
  122. self.distinct_fields = []
  123. self.select_for_update = False
  124. self.select_for_update_nowait = False
  125. self.select_related = False
  126. # SQL aggregate-related attributes
  127. # The _aggregates will be an OrderedDict when used. Due to the cost
  128. # of creating OrderedDict this attribute is created lazily (in
  129. # self.aggregates property).
  130. self._aggregates = None # Maps alias -> SQL aggregate function
  131. self.aggregate_select_mask = None
  132. self._aggregate_select_cache = None
  133. # Arbitrary maximum limit for select_related. Prevents infinite
  134. # recursion. Can be changed by the depth parameter to select_related().
  135. self.max_depth = 5
  136. # These are for extensions. The contents are more or less appended
  137. # verbatim to the appropriate clause.
  138. # The _extra attribute is an OrderedDict, lazily created similarly to
  139. # .aggregates
  140. self._extra = None # Maps col_alias -> (col_sql, params).
  141. self.extra_select_mask = None
  142. self._extra_select_cache = None
  143. self.extra_tables = ()
  144. self.extra_order_by = ()
  145. # A tuple that is a set of model field names and either True, if these
  146. # are the fields to defer, or False if these are the only fields to
  147. # load.
  148. self.deferred_loading = (set(), True)
  149. @property
  150. def extra(self):
  151. if self._extra is None:
  152. self._extra = OrderedDict()
  153. return self._extra
  154. @property
  155. def aggregates(self):
  156. if self._aggregates is None:
  157. self._aggregates = OrderedDict()
  158. return self._aggregates
  159. def __str__(self):
  160. """
  161. Returns the query as a string of SQL with the parameter values
  162. substituted in (use sql_with_params() to see the unsubstituted string).
  163. Parameter values won't necessarily be quoted correctly, since that is
  164. done by the database interface at execution time.
  165. """
  166. sql, params = self.sql_with_params()
  167. return sql % params
  168. def sql_with_params(self):
  169. """
  170. Returns the query as an SQL string and the parameters that will be
  171. substituted into the query.
  172. """
  173. return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
  174. def __deepcopy__(self, memo):
  175. result = self.clone(memo=memo)
  176. memo[id(self)] = result
  177. return result
  178. def prepare(self):
  179. return self
  180. def get_compiler(self, using=None, connection=None):
  181. if using is None and connection is None:
  182. raise ValueError("Need either using or connection")
  183. if using:
  184. connection = connections[using]
  185. # Check that the compiler will be able to execute the query
  186. for alias, aggregate in self.aggregate_select.items():
  187. connection.ops.check_aggregate_support(aggregate)
  188. return connection.ops.compiler(self.compiler)(self, connection, using)
  189. def get_meta(self):
  190. """
  191. Returns the Options instance (the model._meta) from which to start
  192. processing. Normally, this is self.model._meta, but it can be changed
  193. by subclasses.
  194. """
  195. return self.model._meta
  196. def clone(self, klass=None, memo=None, **kwargs):
  197. """
  198. Creates a copy of the current instance. The 'kwargs' parameter can be
  199. used by clients to update attributes after copying has taken place.
  200. """
  201. obj = Empty()
  202. obj.__class__ = klass or self.__class__
  203. obj.model = self.model
  204. obj.alias_refcount = self.alias_refcount.copy()
  205. obj.alias_map = self.alias_map.copy()
  206. obj.table_map = self.table_map.copy()
  207. obj.join_map = self.join_map.copy()
  208. obj.default_cols = self.default_cols
  209. obj.default_ordering = self.default_ordering
  210. obj.standard_ordering = self.standard_ordering
  211. obj.included_inherited_models = self.included_inherited_models.copy()
  212. obj.select = self.select[:]
  213. obj.related_select_cols = []
  214. obj.tables = self.tables[:]
  215. obj.where = self.where.clone()
  216. obj.where_class = self.where_class
  217. if self.group_by is None:
  218. obj.group_by = None
  219. else:
  220. obj.group_by = self.group_by[:]
  221. obj.having = self.having.clone()
  222. obj.order_by = self.order_by[:]
  223. obj.low_mark, obj.high_mark = self.low_mark, self.high_mark
  224. obj.distinct = self.distinct
  225. obj.distinct_fields = self.distinct_fields[:]
  226. obj.select_for_update = self.select_for_update
  227. obj.select_for_update_nowait = self.select_for_update_nowait
  228. obj.select_related = self.select_related
  229. obj.related_select_cols = []
  230. obj._aggregates = self._aggregates.copy() if self._aggregates is not None else None
  231. if self.aggregate_select_mask is None:
  232. obj.aggregate_select_mask = None
  233. else:
  234. obj.aggregate_select_mask = self.aggregate_select_mask.copy()
  235. # _aggregate_select_cache cannot be copied, as doing so breaks the
  236. # (necessary) state in which both aggregates and
  237. # _aggregate_select_cache point to the same underlying objects.
  238. # It will get re-populated in the cloned queryset the next time it's
  239. # used.
  240. obj._aggregate_select_cache = None
  241. obj.max_depth = self.max_depth
  242. obj._extra = self._extra.copy() if self._extra is not None else None
  243. if self.extra_select_mask is None:
  244. obj.extra_select_mask = None
  245. else:
  246. obj.extra_select_mask = self.extra_select_mask.copy()
  247. if self._extra_select_cache is None:
  248. obj._extra_select_cache = None
  249. else:
  250. obj._extra_select_cache = self._extra_select_cache.copy()
  251. obj.extra_tables = self.extra_tables
  252. obj.extra_order_by = self.extra_order_by
  253. obj.deferred_loading = copy.copy(self.deferred_loading[0]), self.deferred_loading[1]
  254. if self.filter_is_sticky and self.used_aliases:
  255. obj.used_aliases = self.used_aliases.copy()
  256. else:
  257. obj.used_aliases = set()
  258. obj.filter_is_sticky = False
  259. if 'alias_prefix' in self.__dict__:
  260. obj.alias_prefix = self.alias_prefix
  261. if 'subq_aliases' in self.__dict__:
  262. obj.subq_aliases = self.subq_aliases.copy()
  263. obj.__dict__.update(kwargs)
  264. if hasattr(obj, '_setup_query'):
  265. obj._setup_query()
  266. return obj
  267. def convert_values(self, value, field, connection):
  268. """Convert the database-returned value into a type that is consistent
  269. across database backends.
  270. By default, this defers to the underlying backend operations, but
  271. it can be overridden by Query classes for specific backends.
  272. """
  273. return connection.ops.convert_values(value, field)
  274. def resolve_aggregate(self, value, aggregate, connection):
  275. """Resolve the value of aggregates returned by the database to
  276. consistent (and reasonable) types.
  277. This is required because of the predisposition of certain backends
  278. to return Decimal and long types when they are not needed.
  279. """
  280. if value is None:
  281. if aggregate.is_ordinal:
  282. return 0
  283. # Return None as-is
  284. return value
  285. elif aggregate.is_ordinal:
  286. # Any ordinal aggregate (e.g., count) returns an int
  287. return int(value)
  288. elif aggregate.is_computed:
  289. # Any computed aggregate (e.g., avg) returns a float
  290. return float(value)
  291. else:
  292. # Return value depends on the type of the field being processed.
  293. return self.convert_values(value, aggregate.field, connection)
  294. def get_aggregation(self, using, force_subq=False):
  295. """
  296. Returns the dictionary with the values of the existing aggregations.
  297. """
  298. if not self.aggregate_select:
  299. return {}
  300. # If there is a group by clause, aggregating does not add useful
  301. # information but retrieves only the first row. Aggregate
  302. # over the subquery instead.
  303. if self.group_by is not None or force_subq:
  304. from django.db.models.sql.subqueries import AggregateQuery
  305. query = AggregateQuery(self.model)
  306. obj = self.clone()
  307. if not force_subq:
  308. # In forced subq case the ordering and limits will likely
  309. # affect the results.
  310. obj.clear_ordering(True)
  311. obj.clear_limits()
  312. obj.select_for_update = False
  313. obj.select_related = False
  314. obj.related_select_cols = []
  315. relabels = dict((t, 'subquery') for t in self.tables)
  316. # Remove any aggregates marked for reduction from the subquery
  317. # and move them to the outer AggregateQuery.
  318. for alias, aggregate in self.aggregate_select.items():
  319. if aggregate.is_summary:
  320. query.aggregates[alias] = aggregate.relabeled_clone(relabels)
  321. del obj.aggregate_select[alias]
  322. try:
  323. query.add_subquery(obj, using)
  324. except EmptyResultSet:
  325. return dict(
  326. (alias, None)
  327. for alias in query.aggregate_select
  328. )
  329. else:
  330. query = self
  331. self.select = []
  332. self.default_cols = False
  333. self._extra = {}
  334. self.remove_inherited_models()
  335. query.clear_ordering(True)
  336. query.clear_limits()
  337. query.select_for_update = False
  338. query.select_related = False
  339. query.related_select_cols = []
  340. result = query.get_compiler(using).execute_sql(SINGLE)
  341. if result is None:
  342. result = [None for q in query.aggregate_select.items()]
  343. return dict(
  344. (alias, self.resolve_aggregate(val, aggregate, connection=connections[using]))
  345. for (alias, aggregate), val
  346. in zip(query.aggregate_select.items(), result)
  347. )
  348. def get_count(self, using):
  349. """
  350. Performs a COUNT() query using the current filter constraints.
  351. """
  352. obj = self.clone()
  353. if len(self.select) > 1 or self.aggregate_select or (self.distinct and self.distinct_fields):
  354. # If a select clause exists, then the query has already started to
  355. # specify the columns that are to be returned.
  356. # In this case, we need to use a subquery to evaluate the count.
  357. from django.db.models.sql.subqueries import AggregateQuery
  358. subquery = obj
  359. subquery.clear_ordering(True)
  360. subquery.clear_limits()
  361. obj = AggregateQuery(obj.model)
  362. try:
  363. obj.add_subquery(subquery, using=using)
  364. except EmptyResultSet:
  365. # add_subquery evaluates the query, if it's an EmptyResultSet
  366. # then there are can be no results, and therefore there the
  367. # count is obviously 0
  368. return 0
  369. obj.add_count_column()
  370. number = obj.get_aggregation(using=using)[None]
  371. # Apply offset and limit constraints manually, since using LIMIT/OFFSET
  372. # in SQL (in variants that provide them) doesn't change the COUNT
  373. # output.
  374. number = max(0, number - self.low_mark)
  375. if self.high_mark is not None:
  376. number = min(number, self.high_mark - self.low_mark)
  377. return number
  378. def has_filters(self):
  379. return self.where or self.having
  380. def has_results(self, using):
  381. q = self.clone()
  382. if not q.distinct:
  383. q.clear_select_clause()
  384. q.clear_ordering(True)
  385. q.set_limits(high=1)
  386. compiler = q.get_compiler(using=using)
  387. return compiler.has_results()
  388. def combine(self, rhs, connector):
  389. """
  390. Merge the 'rhs' query into the current one (with any 'rhs' effects
  391. being applied *after* (that is, "to the right of") anything in the
  392. current query. 'rhs' is not modified during a call to this function.
  393. The 'connector' parameter describes how to connect filters from the
  394. 'rhs' query.
  395. """
  396. assert self.model == rhs.model, \
  397. "Cannot combine queries on two different base models."
  398. assert self.can_filter(), \
  399. "Cannot combine queries once a slice has been taken."
  400. assert self.distinct == rhs.distinct, \
  401. "Cannot combine a unique query with a non-unique query."
  402. assert self.distinct_fields == rhs.distinct_fields, \
  403. "Cannot combine queries with different distinct fields."
  404. self.remove_inherited_models()
  405. # Work out how to relabel the rhs aliases, if necessary.
  406. change_map = {}
  407. conjunction = (connector == AND)
  408. # Determine which existing joins can be reused. When combining the
  409. # query with AND we must recreate all joins for m2m filters. When
  410. # combining with OR we can reuse joins. The reason is that in AND
  411. # case a single row can't fulfill a condition like:
  412. # revrel__col=1 & revrel__col=2
  413. # But, there might be two different related rows matching this
  414. # condition. In OR case a single True is enough, so single row is
  415. # enough, too.
  416. #
  417. # Note that we will be creating duplicate joins for non-m2m joins in
  418. # the AND case. The results will be correct but this creates too many
  419. # joins. This is something that could be fixed later on.
  420. reuse = set() if conjunction else set(self.tables)
  421. # Base table must be present in the query - this is the same
  422. # table on both sides.
  423. self.get_initial_alias()
  424. joinpromoter = JoinPromoter(connector, 2, False)
  425. joinpromoter.add_votes(
  426. j for j in self.alias_map if self.alias_map[j].join_type == self.INNER)
  427. rhs_votes = set()
  428. # Now, add the joins from rhs query into the new query (skipping base
  429. # table).
  430. for alias in rhs.tables[1:]:
  431. table, _, join_type, lhs, join_cols, nullable, join_field = rhs.alias_map[alias]
  432. # If the left side of the join was already relabeled, use the
  433. # updated alias.
  434. lhs = change_map.get(lhs, lhs)
  435. new_alias = self.join(
  436. (lhs, table, join_cols), reuse=reuse,
  437. nullable=nullable, join_field=join_field)
  438. if join_type == self.INNER:
  439. rhs_votes.add(new_alias)
  440. # We can't reuse the same join again in the query. If we have two
  441. # distinct joins for the same connection in rhs query, then the
  442. # combined query must have two joins, too.
  443. reuse.discard(new_alias)
  444. change_map[alias] = new_alias
  445. if not rhs.alias_refcount[alias]:
  446. # The alias was unused in the rhs query. Unref it so that it
  447. # will be unused in the new query, too. We have to add and
  448. # unref the alias so that join promotion has information of
  449. # the join type for the unused alias.
  450. self.unref_alias(new_alias)
  451. joinpromoter.add_votes(rhs_votes)
  452. joinpromoter.update_join_types(self)
  453. # Now relabel a copy of the rhs where-clause and add it to the current
  454. # one.
  455. if rhs.where:
  456. w = rhs.where.clone()
  457. w.relabel_aliases(change_map)
  458. if not self.where:
  459. # Since 'self' matches everything, add an explicit "include
  460. # everything" where-constraint so that connections between the
  461. # where clauses won't exclude valid results.
  462. self.where.add(EverythingNode(), AND)
  463. elif self.where:
  464. # rhs has an empty where clause.
  465. w = self.where_class()
  466. w.add(EverythingNode(), AND)
  467. else:
  468. w = self.where_class()
  469. self.where.add(w, connector)
  470. # Selection columns and extra extensions are those provided by 'rhs'.
  471. self.select = []
  472. for col, field in rhs.select:
  473. if isinstance(col, (list, tuple)):
  474. new_col = change_map.get(col[0], col[0]), col[1]
  475. self.select.append(SelectInfo(new_col, field))
  476. else:
  477. new_col = col.relabeled_clone(change_map)
  478. self.select.append(SelectInfo(new_col, field))
  479. if connector == OR:
  480. # It would be nice to be able to handle this, but the queries don't
  481. # really make sense (or return consistent value sets). Not worth
  482. # the extra complexity when you can write a real query instead.
  483. if self._extra and rhs._extra:
  484. raise ValueError("When merging querysets using 'or', you "
  485. "cannot have extra(select=...) on both sides.")
  486. self.extra.update(rhs.extra)
  487. extra_select_mask = set()
  488. if self.extra_select_mask is not None:
  489. extra_select_mask.update(self.extra_select_mask)
  490. if rhs.extra_select_mask is not None:
  491. extra_select_mask.update(rhs.extra_select_mask)
  492. if extra_select_mask:
  493. self.set_extra_mask(extra_select_mask)
  494. self.extra_tables += rhs.extra_tables
  495. # Ordering uses the 'rhs' ordering, unless it has none, in which case
  496. # the current ordering is used.
  497. self.order_by = rhs.order_by[:] if rhs.order_by else self.order_by
  498. self.extra_order_by = rhs.extra_order_by or self.extra_order_by
  499. def deferred_to_data(self, target, callback):
  500. """
  501. Converts the self.deferred_loading data structure to an alternate data
  502. structure, describing the field that *will* be loaded. This is used to
  503. compute the columns to select from the database and also by the
  504. QuerySet class to work out which fields are being initialized on each
  505. model. Models that have all their fields included aren't mentioned in
  506. the result, only those that have field restrictions in place.
  507. The "target" parameter is the instance that is populated (in place).
  508. The "callback" is a function that is called whenever a (model, field)
  509. pair need to be added to "target". It accepts three parameters:
  510. "target", and the model and list of fields being added for that model.
  511. """
  512. field_names, defer = self.deferred_loading
  513. if not field_names:
  514. return
  515. orig_opts = self.get_meta()
  516. seen = {}
  517. must_include = {orig_opts.concrete_model: set([orig_opts.pk])}
  518. for field_name in field_names:
  519. parts = field_name.split(LOOKUP_SEP)
  520. cur_model = self.model
  521. opts = orig_opts
  522. for name in parts[:-1]:
  523. old_model = cur_model
  524. source = opts.get_field_by_name(name)[0]
  525. if is_reverse_o2o(source):
  526. cur_model = source.model
  527. else:
  528. cur_model = source.rel.to
  529. opts = cur_model._meta
  530. # Even if we're "just passing through" this model, we must add
  531. # both the current model's pk and the related reference field
  532. # (if it's not a reverse relation) to the things we select.
  533. if not is_reverse_o2o(source):
  534. must_include[old_model].add(source)
  535. add_to_dict(must_include, cur_model, opts.pk)
  536. field, model, _, _ = opts.get_field_by_name(parts[-1])
  537. if model is None:
  538. model = cur_model
  539. if not is_reverse_o2o(field):
  540. add_to_dict(seen, model, field)
  541. if defer:
  542. # We need to load all fields for each model, except those that
  543. # appear in "seen" (for all models that appear in "seen"). The only
  544. # slight complexity here is handling fields that exist on parent
  545. # models.
  546. workset = {}
  547. for model, values in six.iteritems(seen):
  548. for field, m in model._meta.get_fields_with_model():
  549. if field in values:
  550. continue
  551. add_to_dict(workset, m or model, field)
  552. for model, values in six.iteritems(must_include):
  553. # If we haven't included a model in workset, we don't add the
  554. # corresponding must_include fields for that model, since an
  555. # empty set means "include all fields". That's why there's no
  556. # "else" branch here.
  557. if model in workset:
  558. workset[model].update(values)
  559. for model, values in six.iteritems(workset):
  560. callback(target, model, values)
  561. else:
  562. for model, values in six.iteritems(must_include):
  563. if model in seen:
  564. seen[model].update(values)
  565. else:
  566. # As we've passed through this model, but not explicitly
  567. # included any fields, we have to make sure it's mentioned
  568. # so that only the "must include" fields are pulled in.
  569. seen[model] = values
  570. # Now ensure that every model in the inheritance chain is mentioned
  571. # in the parent list. Again, it must be mentioned to ensure that
  572. # only "must include" fields are pulled in.
  573. for model in orig_opts.get_parent_list():
  574. if model not in seen:
  575. seen[model] = set()
  576. for model, values in six.iteritems(seen):
  577. callback(target, model, values)
  578. def deferred_to_columns_cb(self, target, model, fields):
  579. """
  580. Callback used by deferred_to_columns(). The "target" parameter should
  581. be a set instance.
  582. """
  583. table = model._meta.db_table
  584. if table not in target:
  585. target[table] = set()
  586. for field in fields:
  587. target[table].add(field.column)
  588. def table_alias(self, table_name, create=False):
  589. """
  590. Returns a table alias for the given table_name and whether this is a
  591. new alias or not.
  592. If 'create' is true, a new alias is always created. Otherwise, the
  593. most recently created alias for the table (if one exists) is reused.
  594. """
  595. current = self.table_map.get(table_name)
  596. if not create and current:
  597. alias = current[0]
  598. self.alias_refcount[alias] += 1
  599. return alias, False
  600. # Create a new alias for this table.
  601. if current:
  602. alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 1)
  603. current.append(alias)
  604. else:
  605. # The first occurrence of a table uses the table name directly.
  606. alias = table_name
  607. self.table_map[alias] = [alias]
  608. self.alias_refcount[alias] = 1
  609. self.tables.append(alias)
  610. return alias, True
  611. def ref_alias(self, alias):
  612. """ Increases the reference count for this alias. """
  613. self.alias_refcount[alias] += 1
  614. def unref_alias(self, alias, amount=1):
  615. """ Decreases the reference count for this alias. """
  616. self.alias_refcount[alias] -= amount
  617. def promote_joins(self, aliases):
  618. """
  619. Promotes recursively the join type of given aliases and its children to
  620. an outer join. If 'unconditional' is False, the join is only promoted if
  621. it is nullable or the parent join is an outer join.
  622. The children promotion is done to avoid join chains that contain a LOUTER
  623. b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted,
  624. then we must also promote b->c automatically, or otherwise the promotion
  625. of a->b doesn't actually change anything in the query results.
  626. """
  627. aliases = list(aliases)
  628. while aliases:
  629. alias = aliases.pop(0)
  630. if self.alias_map[alias].join_cols[0][1] is None:
  631. # This is the base table (first FROM entry) - this table
  632. # isn't really joined at all in the query, so we should not
  633. # alter its join type.
  634. continue
  635. # Only the first alias (skipped above) should have None join_type
  636. assert self.alias_map[alias].join_type is not None
  637. parent_alias = self.alias_map[alias].lhs_alias
  638. parent_louter = (
  639. parent_alias
  640. and self.alias_map[parent_alias].join_type == self.LOUTER)
  641. already_louter = self.alias_map[alias].join_type == self.LOUTER
  642. if ((self.alias_map[alias].nullable or parent_louter) and
  643. not already_louter):
  644. data = self.alias_map[alias]._replace(join_type=self.LOUTER)
  645. self.alias_map[alias] = data
  646. # Join type of 'alias' changed, so re-examine all aliases that
  647. # refer to this one.
  648. aliases.extend(
  649. join for join in self.alias_map.keys()
  650. if (self.alias_map[join].lhs_alias == alias
  651. and join not in aliases))
  652. def demote_joins(self, aliases):
  653. """
  654. Change join type from LOUTER to INNER for all joins in aliases.
  655. Similarly to promote_joins(), this method must ensure no join chains
  656. containing first an outer, then an inner join are generated. If we
  657. are demoting b->c join in chain a LOUTER b LOUTER c then we must
  658. demote a->b automatically, or otherwise the demotion of b->c doesn't
  659. actually change anything in the query results. .
  660. """
  661. aliases = list(aliases)
  662. while aliases:
  663. alias = aliases.pop(0)
  664. if self.alias_map[alias].join_type == self.LOUTER:
  665. self.alias_map[alias] = self.alias_map[alias]._replace(join_type=self.INNER)
  666. parent_alias = self.alias_map[alias].lhs_alias
  667. if self.alias_map[parent_alias].join_type == self.INNER:
  668. aliases.append(parent_alias)
  669. def reset_refcounts(self, to_counts):
  670. """
  671. This method will reset reference counts for aliases so that they match
  672. the value passed in :param to_counts:.
  673. """
  674. for alias, cur_refcount in self.alias_refcount.copy().items():
  675. unref_amount = cur_refcount - to_counts.get(alias, 0)
  676. self.unref_alias(alias, unref_amount)
  677. def change_aliases(self, change_map):
  678. """
  679. Changes the aliases in change_map (which maps old-alias -> new-alias),
  680. relabelling any references to them in select columns and the where
  681. clause.
  682. """
  683. assert set(change_map.keys()).intersection(set(change_map.values())) == set()
  684. def relabel_column(col):
  685. if isinstance(col, (list, tuple)):
  686. old_alias = col[0]
  687. return (change_map.get(old_alias, old_alias), col[1])
  688. else:
  689. return col.relabeled_clone(change_map)
  690. # 1. Update references in "select" (normal columns plus aliases),
  691. # "group by", "where" and "having".
  692. self.where.relabel_aliases(change_map)
  693. self.having.relabel_aliases(change_map)
  694. if self.group_by:
  695. self.group_by = [relabel_column(col) for col in self.group_by]
  696. self.select = [SelectInfo(relabel_column(s.col), s.field)
  697. for s in self.select]
  698. if self._aggregates:
  699. self._aggregates = OrderedDict(
  700. (key, relabel_column(col)) for key, col in self._aggregates.items())
  701. # 2. Rename the alias in the internal table/alias datastructures.
  702. for ident, aliases in self.join_map.items():
  703. del self.join_map[ident]
  704. aliases = tuple(change_map.get(a, a) for a in aliases)
  705. ident = (change_map.get(ident[0], ident[0]),) + ident[1:]
  706. self.join_map[ident] = aliases
  707. for old_alias, new_alias in six.iteritems(change_map):
  708. alias_data = self.alias_map[old_alias]
  709. alias_data = alias_data._replace(rhs_alias=new_alias)
  710. self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
  711. del self.alias_refcount[old_alias]
  712. self.alias_map[new_alias] = alias_data
  713. del self.alias_map[old_alias]
  714. table_aliases = self.table_map[alias_data.table_name]
  715. for pos, alias in enumerate(table_aliases):
  716. if alias == old_alias:
  717. table_aliases[pos] = new_alias
  718. break
  719. for pos, alias in enumerate(self.tables):
  720. if alias == old_alias:
  721. self.tables[pos] = new_alias
  722. break
  723. for key, alias in self.included_inherited_models.items():
  724. if alias in change_map:
  725. self.included_inherited_models[key] = change_map[alias]
  726. # 3. Update any joins that refer to the old alias.
  727. for alias, data in six.iteritems(self.alias_map):
  728. lhs = data.lhs_alias
  729. if lhs in change_map:
  730. data = data._replace(lhs_alias=change_map[lhs])
  731. self.alias_map[alias] = data
  732. def bump_prefix(self, outer_query):
  733. """
  734. Changes the alias prefix to the next letter in the alphabet in a way
  735. that the outer query's aliases and this query's aliases will not
  736. conflict. Even tables that previously had no alias will get an alias
  737. after this call.
  738. """
  739. if self.alias_prefix != outer_query.alias_prefix:
  740. # No clashes between self and outer query should be possible.
  741. return
  742. self.alias_prefix = chr(ord(self.alias_prefix) + 1)
  743. while self.alias_prefix in self.subq_aliases:
  744. self.alias_prefix = chr(ord(self.alias_prefix) + 1)
  745. assert self.alias_prefix < 'Z'
  746. self.subq_aliases = self.subq_aliases.union([self.alias_prefix])
  747. outer_query.subq_aliases = outer_query.subq_aliases.union(self.subq_aliases)
  748. change_map = OrderedDict()
  749. for pos, alias in enumerate(self.tables):
  750. new_alias = '%s%d' % (self.alias_prefix, pos)
  751. change_map[alias] = new_alias
  752. self.tables[pos] = new_alias
  753. self.change_aliases(change_map)
  754. def get_initial_alias(self):
  755. """
  756. Returns the first alias for this query, after increasing its reference
  757. count.
  758. """
  759. if self.tables:
  760. alias = self.tables[0]
  761. self.ref_alias(alias)
  762. else:
  763. alias = self.join((None, self.get_meta().db_table, None))
  764. return alias
  765. def count_active_tables(self):
  766. """
  767. Returns the number of tables in this query with a non-zero reference
  768. count. Note that after execution, the reference counts are zeroed, so
  769. tables added in compiler will not be seen by this method.
  770. """
  771. return len([1 for count in self.alias_refcount.values() if count])
  772. def join(self, connection, reuse=None, nullable=False, join_field=None):
  773. """
  774. Returns an alias for the join in 'connection', either reusing an
  775. existing alias for that join or creating a new one. 'connection' is a
  776. tuple (lhs, table, join_cols) where 'lhs' is either an existing
  777. table alias or a table name. 'join_cols' is a tuple of tuples containing
  778. columns to join on ((l_id1, r_id1), (l_id2, r_id2)). The join corresponds
  779. to the SQL equivalent of::
  780. lhs.l_id1 = table.r_id1 AND lhs.l_id2 = table.r_id2
  781. The 'reuse' parameter can be either None which means all joins
  782. (matching the connection) are reusable, or it can be a set containing
  783. the aliases that can be reused.
  784. A join is always created as LOUTER if the lhs alias is LOUTER to make
  785. sure we do not generate chains like t1 LOUTER t2 INNER t3. All new
  786. joins are created as LOUTER if nullable is True.
  787. If 'nullable' is True, the join can potentially involve NULL values and
  788. is a candidate for promotion (to "left outer") when combining querysets.
  789. The 'join_field' is the field we are joining along (if any).
  790. """
  791. lhs, table, join_cols = connection
  792. assert lhs is None or join_field is not None
  793. existing = self.join_map.get(connection, ())
  794. if reuse is None:
  795. reuse = existing
  796. else:
  797. reuse = [a for a in existing if a in reuse]
  798. for alias in reuse:
  799. if join_field and self.alias_map[alias].join_field != join_field:
  800. # The join_map doesn't contain join_field (mainly because
  801. # fields in Query structs are problematic in pickling), so
  802. # check that the existing join is created using the same
  803. # join_field used for the under work join.
  804. continue
  805. self.ref_alias(alias)
  806. return alias
  807. # No reuse is possible, so we need a new alias.
  808. alias, _ = self.table_alias(table, True)
  809. if not lhs:
  810. # Not all tables need to be joined to anything. No join type
  811. # means the later columns are ignored.
  812. join_type = None
  813. elif self.alias_map[lhs].join_type == self.LOUTER or nullable:
  814. join_type = self.LOUTER
  815. else:
  816. join_type = self.INNER
  817. join = JoinInfo(table, alias, join_type, lhs, join_cols or ((None, None),), nullable,
  818. join_field)
  819. self.alias_map[alias] = join
  820. if connection in self.join_map:
  821. self.join_map[connection] += (alias,)
  822. else:
  823. self.join_map[connection] = (alias,)
  824. return alias
  825. def setup_inherited_models(self):
  826. """
  827. If the model that is the basis for this QuerySet inherits other models,
  828. we need to ensure that those other models have their tables included in
  829. the query.
  830. We do this as a separate step so that subclasses know which
  831. tables are going to be active in the query, without needing to compute
  832. all the select columns (this method is called from pre_sql_setup(),
  833. whereas column determination is a later part, and side-effect, of
  834. as_sql()).
  835. """
  836. opts = self.get_meta()
  837. root_alias = self.tables[0]
  838. seen = {None: root_alias}
  839. for field, model in opts.get_fields_with_model():
  840. if model not in seen:
  841. self.join_parent_model(opts, model, root_alias, seen)
  842. self.included_inherited_models = seen
  843. def join_parent_model(self, opts, model, alias, seen):
  844. """
  845. Makes sure the given 'model' is joined in the query. If 'model' isn't
  846. a parent of 'opts' or if it is None this method is a no-op.
  847. The 'alias' is the root alias for starting the join, 'seen' is a dict
  848. of model -> alias of existing joins. It must also contain a mapping
  849. of None -> some alias. This will be returned in the no-op case.
  850. """
  851. if model in seen:
  852. return seen[model]
  853. chain = opts.get_base_chain(model)
  854. if chain is None:
  855. return alias
  856. curr_opts = opts
  857. for int_model in chain:
  858. if int_model in seen:
  859. return seen[int_model]
  860. # Proxy model have elements in base chain
  861. # with no parents, assign the new options
  862. # object and skip to the next base in that
  863. # case
  864. if not curr_opts.parents[int_model]:
  865. curr_opts = int_model._meta
  866. continue
  867. link_field = curr_opts.get_ancestor_link(int_model)
  868. _, _, _, joins, _ = self.setup_joins(
  869. [link_field.name], curr_opts, alias)
  870. curr_opts = int_model._meta
  871. alias = seen[int_model] = joins[-1]
  872. return alias or seen[None]
  873. def remove_inherited_models(self):
  874. """
  875. Undoes the effects of setup_inherited_models(). Should be called
  876. whenever select columns (self.select) are set explicitly.
  877. """
  878. for key, alias in self.included_inherited_models.items():
  879. if key:
  880. self.unref_alias(alias)
  881. self.included_inherited_models = {}
  882. def add_aggregate(self, aggregate, model, alias, is_summary):
  883. """
  884. Adds a single aggregate expression to the Query
  885. """
  886. opts = model._meta
  887. field_list = aggregate.lookup.split(LOOKUP_SEP)
  888. if len(field_list) == 1 and self._aggregates and aggregate.lookup in self.aggregates:
  889. # Aggregate is over an annotation
  890. field_name = field_list[0]
  891. col = field_name
  892. source = self.aggregates[field_name]
  893. if not is_summary:
  894. raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (
  895. aggregate.name, field_name, field_name))
  896. elif ((len(field_list) > 1) or
  897. (field_list[0] not in [i.name for i in opts.fields]) or
  898. self.group_by is None or
  899. not is_summary):
  900. # If:
  901. # - the field descriptor has more than one part (foo__bar), or
  902. # - the field descriptor is referencing an m2m/m2o field, or
  903. # - this is a reference to a model field (possibly inherited), or
  904. # - this is an annotation over a model field
  905. # then we need to explore the joins that are required.
  906. # Join promotion note - we must not remove any rows here, so use
  907. # outer join if there isn't any existing join.
  908. field, sources, opts, join_list, path = self.setup_joins(
  909. field_list, opts, self.get_initial_alias())
  910. # Process the join chain to see if it can be trimmed
  911. targets, _, join_list = self.trim_joins(sources, join_list, path)
  912. col = targets[0].column
  913. source = sources[0]
  914. col = (join_list[-1], col)
  915. else:
  916. # The simplest cases. No joins required -
  917. # just reference the provided column alias.
  918. field_name = field_list[0]
  919. source = opts.get_field(field_name)
  920. col = field_name
  921. # We want to have the alias in SELECT clause even if mask is set.
  922. self.append_aggregate_mask([alias])
  923. # Add the aggregate to the query
  924. aggregate.add_to_query(self, alias, col=col, source=source, is_summary=is_summary)
  925. def prepare_lookup_value(self, value, lookups, can_reuse):
  926. # Default lookup if none given is exact.
  927. if len(lookups) == 0:
  928. lookups = ['exact']
  929. # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
  930. # uses of None as a query value.
  931. if value is None:
  932. if lookups[-1] not in ('exact', 'iexact'):
  933. raise ValueError("Cannot use None as a query value")
  934. lookups[-1] = 'isnull'
  935. value = True
  936. elif callable(value):
  937. warnings.warn(
  938. "Passing callable arguments to queryset is deprecated.",
  939. RemovedInDjango19Warning, stacklevel=2)
  940. value = value()
  941. elif isinstance(value, ExpressionNode):
  942. # If value is a query expression, evaluate it
  943. value = SQLEvaluator(value, self, reuse=can_reuse)
  944. if hasattr(value, 'query') and hasattr(value.query, 'bump_prefix'):
  945. value = value._clone()
  946. value.query.bump_prefix(self)
  947. if hasattr(value, 'bump_prefix'):
  948. value = value.clone()
  949. value.bump_prefix(self)
  950. # For Oracle '' is equivalent to null. The check needs to be done
  951. # at this stage because join promotion can't be done at compiler
  952. # stage. Using DEFAULT_DB_ALIAS isn't nice, but it is the best we
  953. # can do here. Similar thing is done in is_nullable(), too.
  954. if (connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and
  955. lookups[-1] == 'exact' and value == ''):
  956. value = True
  957. lookups[-1] = 'isnull'
  958. return value, lookups
  959. def solve_lookup_type(self, lookup):
  960. """
  961. Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
  962. """
  963. lookup_splitted = lookup.split(LOOKUP_SEP)
  964. if self._aggregates:
  965. aggregate, aggregate_lookups = refs_aggregate(lookup_splitted, self.aggregates)
  966. if aggregate:
  967. return aggregate_lookups, (), aggregate
  968. _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  969. field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
  970. if len(lookup_parts) == 0:
  971. lookup_parts = ['exact']
  972. elif len(lookup_parts) > 1:
  973. if not field_parts:
  974. raise FieldError(
  975. 'Invalid lookup "%s" for model %s".' %
  976. (lookup, self.get_meta().model.__name__))
  977. return lookup_parts, field_parts, False
  978. def build_lookup(self, lookups, lhs, rhs):
  979. lookups = lookups[:]
  980. while lookups:
  981. lookup = lookups[0]
  982. if len(lookups) == 1:
  983. final_lookup = lhs.get_lookup(lookup)
  984. if final_lookup:
  985. return final_lookup(lhs, rhs)
  986. # We didn't find a lookup, so we are going to try get_transform
  987. # + get_lookup('exact').
  988. lookups.append('exact')
  989. next = lhs.get_transform(lookup)
  990. if next:
  991. lhs = next(lhs, lookups)
  992. else:
  993. raise FieldError(
  994. "Unsupported lookup '%s' for %s or join on the field not "
  995. "permitted." %
  996. (lookup, lhs.output_field.__class__.__name__))
  997. lookups = lookups[1:]
  998. def build_filter(self, filter_expr, branch_negated=False, current_negated=False,
  999. can_reuse=None, connector=AND):
  1000. """
  1001. Builds a WhereNode for a single filter clause, but doesn't add it
  1002. to this Query. Query.add_q() will then add this filter to the where
  1003. or having Node.
  1004. The 'branch_negated' tells us if the current branch contains any
  1005. negations. This will be used to determine if subqueries are needed.
  1006. The 'current_negated' is used to determine if the current filter is
  1007. negated or not and this will be used to determine if IS NULL filtering
  1008. is needed.
  1009. The difference between current_netageted and branch_negated is that
  1010. branch_negated is set on first negation, but current_negated is
  1011. flipped for each negation.
  1012. Note that add_filter will not do any negating itself, that is done
  1013. upper in the code by add_q().
  1014. The 'can_reuse' is a set of reusable joins for multijoins.
  1015. The method will create a filter clause that can be added to the current
  1016. query. However, if the filter isn't added to the query then the caller
  1017. is responsible for unreffing the joins used.
  1018. """
  1019. arg, value = filter_expr
  1020. if not arg:
  1021. raise FieldError("Cannot parse keyword query %r" % arg)
  1022. lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
  1023. # Work out the lookup type and remove it from the end of 'parts',
  1024. # if necessary.
  1025. value, lookups = self.prepare_lookup_value(value, lookups, can_reuse)
  1026. used_joins = getattr(value, '_used_joins', [])
  1027. clause = self.where_class()
  1028. if reffed_aggregate:
  1029. condition = self.build_lookup(lookups, reffed_aggregate, value)
  1030. if not condition:
  1031. # Backwards compat for custom lookups
  1032. assert len(lookups) == 1
  1033. condition = (reffed_aggregate, lookups[0], value)
  1034. clause.add(condition, AND)
  1035. return clause, []
  1036. opts = self.get_meta()
  1037. alias = self.get_initial_alias()
  1038. allow_many = not branch_negated
  1039. try:
  1040. field, sources, opts, join_list, path = self.setup_joins(
  1041. parts, opts, alias, can_reuse, allow_many)
  1042. # split_exclude() needs to know which joins were generated for the
  1043. # lookup parts
  1044. self._lookup_joins = join_list
  1045. except MultiJoin as e:
  1046. return self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
  1047. can_reuse, e.names_with_path)
  1048. if can_reuse is not None:
  1049. can_reuse.update(join_list)
  1050. used_joins = set(used_joins).union(set(join_list))
  1051. # Process the join list to see if we can remove any non-needed joins from
  1052. # the far end (fewer tables in a query is better).
  1053. targets, alias, join_list = self.trim_joins(sources, join_list, path)
  1054. if hasattr(field, 'get_lookup_constraint'):
  1055. # For now foreign keys get special treatment. This should be
  1056. # refactored when composite fields lands.
  1057. condition = field.get_lookup_constraint(self.where_class, alias, targets, sources,
  1058. lookups, value)
  1059. lookup_type = lookups[-1]
  1060. else:
  1061. assert(len(targets) == 1)
  1062. col = Col(alias, targets[0], field)
  1063. condition = self.build_lookup(lookups, col, value)
  1064. if not condition:
  1065. # Backwards compat for custom lookups
  1066. if lookups[0] not in self.query_terms:
  1067. raise FieldError(
  1068. "Join on field '%s' not permitted. Did you "
  1069. "misspell '%s' for the lookup type?" %
  1070. (col.output_field.name, lookups[0]))
  1071. if len(lookups) > 1:
  1072. raise FieldError("Nested lookup '%s' not supported." %
  1073. LOOKUP_SEP.join(lookups))
  1074. condition = (Constraint(alias, targets[0].column, field), lookups[0], value)
  1075. lookup_type = lookups[-1]
  1076. else:
  1077. lookup_type = condition.lookup_name
  1078. clause.add(condition, AND)
  1079. require_outer = lookup_type == 'isnull' and value is True and not current_negated
  1080. if current_negated and (lookup_type != 'isnull' or value is False):
  1081. require_outer = True
  1082. if (lookup_type != 'isnull' and (
  1083. self.is_nullable(targets[0]) or
  1084. self.alias_map[join_list[-1]].join_type == self.LOUTER)):
  1085. # The condition added here will be SQL like this:
  1086. # NOT (col IS NOT NULL), where the first NOT is added in
  1087. # upper layers of code. The reason for addition is that if col
  1088. # is null, then col != someval will result in SQL "unknown"
  1089. # which isn't the same as in Python. The Python None handling
  1090. # is wanted, and it can be gotten by
  1091. # (col IS NULL OR col != someval)
  1092. # <=>
  1093. # NOT (col IS NOT NULL AND col = someval).
  1094. lookup_class = targets[0].get_lookup('isnull')
  1095. clause.add(lookup_class(Col(alias, targets[0], sources[0]), False), AND)
  1096. return clause, used_joins if not require_outer else ()
  1097. def add_filter(self, filter_clause):
  1098. self.add_q(Q(**{filter_clause[0]: filter_clause[1]}))
  1099. def need_having(self, obj):
  1100. """
  1101. Returns whether or not all elements of this q_object need to be put
  1102. together in the HAVING clause.
  1103. """
  1104. if not self._aggregates:
  1105. return False
  1106. if not isinstance(obj, Node):
  1107. return (refs_aggregate(obj[0].split(LOOKUP_SEP), self.aggregates)[0]
  1108. or (hasattr(obj[1], 'contains_aggregate')
  1109. and obj[1].contains_aggregate(self.aggregates)))
  1110. return any(self.need_having(c) for c in obj.children)
  1111. def split_having_parts(self, q_object, negated=False):
  1112. """
  1113. Returns a list of q_objects which need to go into the having clause
  1114. instead of the where clause. Removes the splitted out nodes from the
  1115. given q_object. Note that the q_object is altered, so cloning it is
  1116. needed.
  1117. """
  1118. having_parts = []
  1119. for c in q_object.children[:]:
  1120. # When constructing the having nodes we need to take care to
  1121. # preserve the negation status from the upper parts of the tree
  1122. if isinstance(c, Node):
  1123. # For each negated child, flip the in_negated flag.
  1124. in_negated = c.negated ^ negated
  1125. if c.connector == OR and self.need_having(c):
  1126. # A subtree starting from OR clause must go into having in
  1127. # whole if any part of that tree references an aggregate.
  1128. q_object.children.remove(c)
  1129. having_parts.append(c)
  1130. c.negated = in_negated
  1131. else:
  1132. having_parts.extend(
  1133. self.split_having_parts(c, in_negated)[1])
  1134. elif self.need_having(c):
  1135. q_object.children.remove(c)
  1136. new_q = self.where_class(children=[c], negated=negated)
  1137. having_parts.append(new_q)
  1138. return q_object, having_parts
  1139. def add_q(self, q_object):
  1140. """
  1141. A preprocessor for the internal _add_q(). Responsible for
  1142. splitting the given q_object into where and having parts and
  1143. setting up some internal variables.
  1144. """
  1145. if not self.need_having(q_object):
  1146. where_part, having_parts = q_object, []
  1147. else:
  1148. where_part, having_parts = self.split_having_parts(
  1149. q_object.clone(), q_object.negated)
  1150. # For join promotion this case is doing an AND for the added q_object
  1151. # and existing conditions. So, any existing inner join forces the join
  1152. # type to remain inner. Existing outer joins can however be demoted.
  1153. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
  1154. # rel_a doesn't produce any rows, then the whole condition must fail.
  1155. # So, demotion is OK.
  1156. existing_inner = set(
  1157. (a for a in self.alias_map if self.alias_map[a].join_type == self.INNER))
  1158. clause, require_inner = self._add_q(where_part, self.used_aliases)
  1159. self.where.add(clause, AND)
  1160. for hp in having_parts:
  1161. clause, _ = self._add_q(hp, self.used_aliases)
  1162. self.having.add(clause, AND)
  1163. self.demote_joins(existing_inner)
  1164. def _add_q(self, q_object, used_aliases, branch_negated=False,
  1165. current_negated=False):
  1166. """
  1167. Adds a Q-object to the current filter.
  1168. """
  1169. connector = q_object.connector
  1170. current_negated = current_negated ^ q_object.negated
  1171. branch_negated = branch_negated or q_object.negated
  1172. target_clause = self.where_class(connector=connector,
  1173. negated=q_object.negated)
  1174. joinpromoter = JoinPromoter(q_object.connector, len(q_object.children), current_negated)
  1175. for child in q_object.children:
  1176. if isinstance(child, Node):
  1177. child_clause, needed_inner = self._add_q(
  1178. child, used_aliases, branch_negated,
  1179. current_negated)
  1180. joinpromoter.add_votes(needed_inner)
  1181. else:
  1182. child_clause, needed_inner = self.build_filter(
  1183. child, can_reuse=used_aliases, branch_negated=branch_negated,
  1184. current_negated=current_negated, connector=connector)
  1185. joinpromoter.add_votes(needed_inner)
  1186. target_clause.add(child_clause, connector)
  1187. needed_inner = joinpromoter.update_join_types(self)
  1188. return target_clause, needed_inner
  1189. def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):
  1190. """
  1191. Walks the names path and turns them PathInfo tuples. Note that a
  1192. single name in 'names' can generate multiple PathInfos (m2m for
  1193. example).
  1194. 'names' is the path of names to travel, 'opts' is the model Options we
  1195. start the name resolving from, 'allow_many' is as for setup_joins().
  1196. Returns a list of PathInfo tuples. In addition returns the final field
  1197. (the last used join field), and target (which is a field guaranteed to
  1198. contain the same value as the final field).
  1199. """
  1200. path, names_with_path = [], []
  1201. for pos, name in enumerate(names):
  1202. cur_names_with_path = (name, [])
  1203. if name == 'pk':
  1204. name = opts.pk.name
  1205. try:
  1206. field, model, direct, m2m = opts.get_field_by_name(name)
  1207. except FieldDoesNotExist:
  1208. # We didn't found the current field, so move position back
  1209. # one step.
  1210. pos -= 1
  1211. break
  1212. # Check if we need any joins for concrete inheritance cases (the
  1213. # field lives in parent, but we are currently in one of its
  1214. # children)
  1215. if model:
  1216. # The field lives on a base class of the current model.
  1217. # Skip the chain of proxy to the concrete proxied model
  1218. proxied_model = opts.concrete_model
  1219. for int_model in opts.get_base_chain(model):
  1220. if int_model is proxied_model:
  1221. opts = int_model._meta
  1222. else:
  1223. final_field = opts.parents[int_model]
  1224. targets = (final_field.rel.get_related_field(),)
  1225. opts = int_model._meta
  1226. path.append(PathInfo(final_field.model._meta, opts, targets, final_field, False, True))
  1227. cur_names_with_path[1].append(PathInfo(final_field.model._meta, opts, targets, final_field, False, True))
  1228. if hasattr(field, 'get_path_info'):
  1229. pathinfos = field.get_path_info()
  1230. if not allow_many:
  1231. for inner_pos, p in enumerate(pathinfos):
  1232. if p.m2m:
  1233. cur_names_with_path[1].extend(pathinfos[0:inner_pos + 1])
  1234. names_with_path.append(cur_names_with_path)
  1235. raise MultiJoin(pos + 1, names_with_path)
  1236. last = pathinfos[-1]
  1237. path.extend(pathinfos)
  1238. final_field = last.join_field
  1239. opts = last.to_opts
  1240. targets = last.target_fields
  1241. cur_names_with_path[1].extend(pathinfos)
  1242. names_with_path.append(cur_names_with_path)
  1243. else:
  1244. # Local non-relational field.
  1245. final_field = field
  1246. targets = (field,)
  1247. break
  1248. if pos == -1 or (fail_on_missing and pos + 1 != len(names)):
  1249. self.raise_field_error(opts, name)
  1250. return path, final_field, targets, names[pos + 1:]
  1251. def raise_field_error(self, opts, name):
  1252. available = opts.get_all_field_names() + list(self.aggregate_select)
  1253. raise FieldError("Cannot resolve keyword %r into field. "
  1254. "Choices are: %s" % (name, ", ".join(available)))
  1255. def setup_joins(self, names, opts, alias, can_reuse=None, allow_many=True):
  1256. """
  1257. Compute the necessary table joins for the passage through the fields
  1258. given in 'names'. 'opts' is the Options class for the current model
  1259. (which gives the table we are starting from), 'alias' is the alias for
  1260. the table to start the joining from.
  1261. The 'can_reuse' defines the reverse foreign key joins we can reuse. It
  1262. can be None in which case all joins are reusable or a set of aliases
  1263. that can be reused. Note that non-reverse foreign keys are always
  1264. reusable when using setup_joins().
  1265. If 'allow_many' is False, then any reverse foreign key seen will
  1266. generate a MultiJoin exception.
  1267. Returns the final field involved in the joins, the target field (used
  1268. for any 'where' constraint), the final 'opts' value, the joins and the
  1269. field path travelled to generate the joins.
  1270. The target field is the field containing the concrete value. Final
  1271. field can be something different, for example foreign key pointing to
  1272. that value. Final field is needed for example in some value
  1273. conversions (convert 'obj' in fk__id=obj to pk val using the foreign
  1274. key field for example).
  1275. """
  1276. joins = [alias]
  1277. # First, generate the path for the names
  1278. path, final_field, targets, rest = self.names_to_path(
  1279. names, opts, allow_many, fail_on_missing=True)
  1280. # Then, add the path to the query's joins. Note that we can't trim
  1281. # joins at this stage - we will need the information about join type
  1282. # of the trimmed joins.
  1283. for pos, join in enumerate(path):
  1284. opts = join.to_opts
  1285. if join.direct:
  1286. nullable = self.is_nullable(join.join_field)
  1287. else:
  1288. nullable = True
  1289. connection = alias, opts.db_table, join.join_field.get_joining_columns()
  1290. reuse = can_reuse if join.m2m else None
  1291. alias = self.join(
  1292. connection, reuse=reuse, nullable=nullable, join_field=join.join_field)
  1293. joins.append(alias)
  1294. if hasattr(final_field, 'field'):
  1295. final_field = final_field.field
  1296. return final_field, targets, opts, joins, path
  1297. def trim_joins(self, targets, joins, path):
  1298. """
  1299. The 'target' parameter is the final field being joined to, 'joins'
  1300. is the full list of join aliases. The 'path' contain the PathInfos
  1301. used to create the joins.
  1302. Returns the final target field and table alias and the new active
  1303. joins.
  1304. We will always trim any direct join if we have the target column
  1305. available already in the previous table. Reverse joins can't be
  1306. trimmed as we don't know if there is anything on the other side of
  1307. the join.
  1308. """
  1309. joins = joins[:]
  1310. for pos, info in enumerate(reversed(path)):
  1311. if len(joins) == 1 or not info.direct:
  1312. break
  1313. join_targets = set(t.column for t in info.join_field.foreign_related_fields)
  1314. cur_targets = set(t.column for t in targets)
  1315. if not cur_targets.issubset(join_targets):
  1316. break
  1317. targets = tuple(r[0] for r in info.join_field.related_fields if r[1].column in cur_targets)
  1318. self.unref_alias(joins.pop())
  1319. return targets, joins[-1], joins
  1320. def split_exclude(self, filter_expr, prefix, can_reuse, names_with_path):
  1321. """
  1322. When doing an exclude against any kind of N-to-many relation, we need
  1323. to use a subquery. This method constructs the nested query, given the
  1324. original exclude filter (filter_expr) and the portion up to the first
  1325. N-to-many relation field.
  1326. As an example we could have original filter ~Q(child__name='foo').
  1327. We would get here with filter_expr = child__name, prefix = child and
  1328. can_reuse is a set of joins usable for filters in the original query.
  1329. We will turn this into equivalent of:
  1330. WHERE NOT (pk IN (SELECT parent_id FROM thetable
  1331. WHERE name = 'foo' AND parent_id IS NOT NULL))
  1332. It might be worth it to consider using WHERE NOT EXISTS as that has
  1333. saner null handling, and is easier for the backend's optimizer to
  1334. handle.
  1335. """
  1336. # Generate the inner query.
  1337. query = Query(self.model)
  1338. query.add_filter(filter_expr)
  1339. query.clear_ordering(True)
  1340. # Try to have as simple as possible subquery -> trim leading joins from
  1341. # the subquery.
  1342. trimmed_prefix, contains_louter = query.trim_start(names_with_path)
  1343. query.remove_inherited_models()
  1344. # Add extra check to make sure the selected field will not be null
  1345. # since we are adding an IN <subquery> clause. This prevents the
  1346. # database from tripping over IN (...,NULL,...) selects and returning
  1347. # nothing
  1348. alias, col = query.select[0].col
  1349. if self.is_nullable(query.select[0].field):
  1350. lookup_class = query.select[0].field.get_lookup('isnull')
  1351. lookup = lookup_class(Col(alias, query.select[0].field, query.select[0].field), False)
  1352. query.where.add(lookup, AND)
  1353. if alias in can_reuse:
  1354. select_field = query.select[0].field
  1355. pk = select_field.model._meta.pk
  1356. # Need to add a restriction so that outer query's filters are in effect for
  1357. # the subquery, too.
  1358. query.bump_prefix(self)
  1359. lookup_class = select_field.get_lookup('exact')
  1360. lookup = lookup_class(Col(query.select[0].col[0], pk, pk),
  1361. Col(alias, pk, pk))
  1362. query.where.add(lookup, AND)
  1363. condition, needed_inner = self.build_filter(
  1364. ('%s__in' % trimmed_prefix, query),
  1365. current_negated=True, branch_negated=True, can_reuse=can_reuse)
  1366. if contains_louter:
  1367. or_null_condition, _ = self.build_filter(
  1368. ('%s__isnull' % trimmed_prefix, True),
  1369. current_negated=True, branch_negated=True, can_reuse=can_reuse)
  1370. condition.add(or_null_condition, OR)
  1371. # Note that the end result will be:
  1372. # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL.
  1373. # This might look crazy but due to how IN works, this seems to be
  1374. # correct. If the IS NOT NULL check is removed then outercol NOT
  1375. # IN will return UNKNOWN. If the IS NULL check is removed, then if
  1376. # outercol IS NULL we will not match the row.
  1377. return condition, needed_inner
  1378. def set_empty(self):
  1379. self.where = EmptyWhere()
  1380. self.having = EmptyWhere()
  1381. def is_empty(self):
  1382. return isinstance(self.where, EmptyWhere) or isinstance(self.having, EmptyWhere)
  1383. def set_limits(self, low=None, high=None):
  1384. """
  1385. Adjusts the limits on the rows retrieved. We use low/high to set these,
  1386. as it makes it more Pythonic to read and write. When the SQL query is
  1387. created, they are converted to the appropriate offset and limit values.
  1388. Any limits passed in here are applied relative to the existing
  1389. constraints. So low is added to the current low value and both will be
  1390. clamped to any existing high value.
  1391. """
  1392. if high is not None:
  1393. if self.high_mark is not None:
  1394. self.high_mark = min(self.high_mark, self.low_mark + high)
  1395. else:
  1396. self.high_mark = self.low_mark + high
  1397. if low is not None:
  1398. if self.high_mark is not None:
  1399. self.low_mark = min(self.high_mark, self.low_mark + low)
  1400. else:
  1401. self.low_mark = self.low_mark + low
  1402. def clear_limits(self):
  1403. """
  1404. Clears any existing limits.
  1405. """
  1406. self.low_mark, self.high_mark = 0, None
  1407. def can_filter(self):
  1408. """
  1409. Returns True if adding filters to this instance is still possible.
  1410. Typically, this means no limits or offsets have been put on the results.
  1411. """
  1412. return not self.low_mark and self.high_mark is None
  1413. def clear_select_clause(self):
  1414. """
  1415. Removes all fields from SELECT clause.
  1416. """
  1417. self.select = []
  1418. self.default_cols = False
  1419. self.select_related = False
  1420. self.set_extra_mask(())
  1421. self.set_aggregate_mask(())
  1422. def clear_select_fields(self):
  1423. """
  1424. Clears the list of fields to select (but not extra_select columns).
  1425. Some queryset types completely replace any existing list of select
  1426. columns.
  1427. """
  1428. self.select = []
  1429. def add_distinct_fields(self, *field_names):
  1430. """
  1431. Adds and resolves the given fields to the query's "distinct on" clause.
  1432. """
  1433. self.distinct_fields = field_names
  1434. self.distinct = True
  1435. def add_fields(self, field_names, allow_m2m=True):
  1436. """
  1437. Adds the given (model) fields to the select set. The field names are
  1438. added in the order specified.
  1439. """
  1440. alias = self.get_initial_alias()
  1441. opts = self.get_meta()
  1442. try:
  1443. for name in field_names:
  1444. # Join promotion note - we must not remove any rows here, so
  1445. # if there is no existing joins, use outer join.
  1446. field, targets, u2, joins, path = self.setup_joins(
  1447. name.split(LOOKUP_SEP), opts, alias, can_reuse=None,
  1448. allow_many=allow_m2m)
  1449. targets, final_alias, joins = self.trim_joins(targets, joins, path)
  1450. for target in targets:
  1451. self.select.append(SelectInfo((final_alias, target.column), target))
  1452. except MultiJoin:
  1453. raise FieldError("Invalid field name: '%s'" % name)
  1454. except FieldError:
  1455. if LOOKUP_SEP in name:
  1456. # For lookups spanning over relationships, show the error
  1457. # from the model on which the lookup failed.
  1458. raise
  1459. else:
  1460. names = sorted(opts.get_all_field_names() + list(self.extra)
  1461. + list(self.aggregate_select))
  1462. raise FieldError("Cannot resolve keyword %r into field. "
  1463. "Choices are: %s" % (name, ", ".join(names)))
  1464. self.remove_inherited_models()
  1465. def add_ordering(self, *ordering):
  1466. """
  1467. Adds items from the 'ordering' sequence to the query's "order by"
  1468. clause. These items are either field names (not column names) --
  1469. possibly with a direction prefix ('-' or '?') -- or ordinals,
  1470. corresponding to column positions in the 'select' list.
  1471. If 'ordering' is empty, all ordering is cleared from the query.
  1472. """
  1473. errors = []
  1474. for item in ordering:
  1475. if not ORDER_PATTERN.match(item):
  1476. errors.append(item)
  1477. if errors:
  1478. raise FieldError('Invalid order_by arguments: %s' % errors)
  1479. if ordering:
  1480. self.order_by.extend(ordering)
  1481. else:
  1482. self.default_ordering = False
  1483. def clear_ordering(self, force_empty):
  1484. """
  1485. Removes any ordering settings. If 'force_empty' is True, there will be
  1486. no ordering in the resulting query (not even the model's default).
  1487. """
  1488. self.order_by = []
  1489. self.extra_order_by = ()
  1490. if force_empty:
  1491. self.default_ordering = False
  1492. def set_group_by(self):
  1493. """
  1494. Expands the GROUP BY clause required by the query.
  1495. This will usually be the set of all non-aggregate fields in the
  1496. return data. If the database backend supports grouping by the
  1497. primary key, and the query would be equivalent, the optimization
  1498. will be made automatically.
  1499. """
  1500. self.group_by = []
  1501. for col, _ in self.select:
  1502. self.group_by.append(col)
  1503. def add_count_column(self):
  1504. """
  1505. Converts the query to do count(...) or count(distinct(pk)) in order to
  1506. get its size.
  1507. """
  1508. if not self.distinct:
  1509. if not self.select:
  1510. count = self.aggregates_module.Count('*', is_summary=True)
  1511. else:
  1512. assert len(self.select) == 1, \
  1513. "Cannot add count col with multiple cols in 'select': %r" % self.select
  1514. count = self.aggregates_module.Count(self.select[0].col)
  1515. else:
  1516. opts = self.get_meta()
  1517. if not self.select:
  1518. count = self.aggregates_module.Count(
  1519. (self.join((None, opts.db_table, None)), opts.pk.column),
  1520. is_summary=True, distinct=True)
  1521. else:
  1522. # Because of SQL portability issues, multi-column, distinct
  1523. # counts need a sub-query -- see get_count() for details.
  1524. assert len(self.select) == 1, \
  1525. "Cannot add count col with multiple cols in 'select'."
  1526. count = self.aggregates_module.Count(self.select[0].col, distinct=True)
  1527. # Distinct handling is done in Count(), so don't do it at this
  1528. # level.
  1529. self.distinct = False
  1530. # Set only aggregate to be the count column.
  1531. # Clear out the select cache to reflect the new unmasked aggregates.
  1532. self._aggregates = {None: count}
  1533. self.set_aggregate_mask(None)
  1534. self.group_by = None
  1535. def add_select_related(self, fields):
  1536. """
  1537. Sets up the select_related data structure so that we only select
  1538. certain related models (as opposed to all models, when
  1539. self.select_related=True).
  1540. """
  1541. if isinstance(self.select_related, bool):
  1542. field_dict = {}
  1543. else:
  1544. field_dict = self.select_related
  1545. for field in fields:
  1546. d = field_dict
  1547. for part in field.split(LOOKUP_SEP):
  1548. d = d.setdefault(part, {})
  1549. self.select_related = field_dict
  1550. self.related_select_cols = []
  1551. def add_extra(self, select, select_params, where, params, tables, order_by):
  1552. """
  1553. Adds data to the various extra_* attributes for user-created additions
  1554. to the query.
  1555. """
  1556. if select:
  1557. # We need to pair any placeholder markers in the 'select'
  1558. # dictionary with their parameters in 'select_params' so that
  1559. # subsequent updates to the select dictionary also adjust the
  1560. # parameters appropriately.
  1561. select_pairs = OrderedDict()
  1562. if select_params:
  1563. param_iter = iter(select_params)
  1564. else:
  1565. param_iter = iter([])
  1566. for name, entry in select.items():
  1567. entry = force_text(entry)
  1568. entry_params = []
  1569. pos = entry.find("%s")
  1570. while pos != -1:
  1571. entry_params.append(next(param_iter))
  1572. pos = entry.find("%s", pos + 2)
  1573. select_pairs[name] = (entry, entry_params)
  1574. # This is order preserving, since self.extra_select is an OrderedDict.
  1575. self.extra.update(select_pairs)
  1576. if where or params:
  1577. self.where.add(ExtraWhere(where, params), AND)
  1578. if tables:
  1579. self.extra_tables += tuple(tables)
  1580. if order_by:
  1581. self.extra_order_by = order_by
  1582. def clear_deferred_loading(self):
  1583. """
  1584. Remove any fields from the deferred loading set.
  1585. """
  1586. self.deferred_loading = (set(), True)
  1587. def add_deferred_loading(self, field_names):
  1588. """
  1589. Add the given list of model field names to the set of fields to
  1590. exclude from loading from the database when automatic column selection
  1591. is done. The new field names are added to any existing field names that
  1592. are deferred (or removed from any existing field names that are marked
  1593. as the only ones for immediate loading).
  1594. """
  1595. # Fields on related models are stored in the literal double-underscore
  1596. # format, so that we can use a set datastructure. We do the foo__bar
  1597. # splitting and handling when computing the SQL column names (as part of
  1598. # get_columns()).
  1599. existing, defer = self.deferred_loading
  1600. if defer:
  1601. # Add to existing deferred names.
  1602. self.deferred_loading = existing.union(field_names), True
  1603. else:
  1604. # Remove names from the set of any existing "immediate load" names.
  1605. self.deferred_loading = existing.difference(field_names), False
  1606. def add_immediate_loading(self, field_names):
  1607. """
  1608. Add the given list of model field names to the set of fields to
  1609. retrieve when the SQL is executed ("immediate loading" fields). The
  1610. field names replace any existing immediate loading field names. If
  1611. there are field names already specified for deferred loading, those
  1612. names are removed from the new field_names before storing the new names
  1613. for immediate loading. (That is, immediate loading overrides any
  1614. existing immediate values, but respects existing deferrals.)
  1615. """
  1616. existing, defer = self.deferred_loading
  1617. field_names = set(field_names)
  1618. if 'pk' in field_names:
  1619. field_names.remove('pk')
  1620. field_names.add(self.get_meta().pk.name)
  1621. if defer:
  1622. # Remove any existing deferred names from the current set before
  1623. # setting the new names.
  1624. self.deferred_loading = field_names.difference(existing), False
  1625. else:
  1626. # Replace any existing "immediate load" field names.
  1627. self.deferred_loading = field_names, False
  1628. def get_loaded_field_names(self):
  1629. """
  1630. If any fields are marked to be deferred, returns a dictionary mapping
  1631. models to a set of names in those fields that will be loaded. If a
  1632. model is not in the returned dictionary, none of its fields are
  1633. deferred.
  1634. If no fields are marked for deferral, returns an empty dictionary.
  1635. """
  1636. # We cache this because we call this function multiple times
  1637. # (compiler.fill_related_selections, query.iterator)
  1638. try:
  1639. return self._loaded_field_names_cache
  1640. except AttributeError:
  1641. collection = {}
  1642. self.deferred_to_data(collection, self.get_loaded_field_names_cb)
  1643. self._loaded_field_names_cache = collection
  1644. return collection
  1645. def get_loaded_field_names_cb(self, target, model, fields):
  1646. """
  1647. Callback used by get_deferred_field_names().
  1648. """
  1649. target[model] = set(f.name for f in fields)
  1650. def set_aggregate_mask(self, names):
  1651. "Set the mask of aggregates that will actually be returned by the SELECT"
  1652. if names is None:
  1653. self.aggregate_select_mask = None
  1654. else:
  1655. self.aggregate_select_mask = set(names)
  1656. self._aggregate_select_cache = None
  1657. def append_aggregate_mask(self, names):
  1658. if self.aggregate_select_mask is not None:
  1659. self.set_aggregate_mask(set(names).union(self.aggregate_select_mask))
  1660. def set_extra_mask(self, names):
  1661. """
  1662. Set the mask of extra select items that will be returned by SELECT,
  1663. we don't actually remove them from the Query since they might be used
  1664. later
  1665. """
  1666. if names is None:
  1667. self.extra_select_mask = None
  1668. else:
  1669. self.extra_select_mask = set(names)
  1670. self._extra_select_cache = None
  1671. @property
  1672. def aggregate_select(self):
  1673. """The OrderedDict of aggregate columns that are not masked, and should
  1674. be used in the SELECT clause.
  1675. This result is cached for optimization purposes.
  1676. """
  1677. if self._aggregate_select_cache is not None:
  1678. return self._aggregate_select_cache
  1679. elif not self._aggregates:
  1680. return {}
  1681. elif self.aggregate_select_mask is not None:
  1682. self._aggregate_select_cache = OrderedDict(
  1683. (k, v) for k, v in self.aggregates.items()
  1684. if k in self.aggregate_select_mask
  1685. )
  1686. return self._aggregate_select_cache
  1687. else:
  1688. return self.aggregates
  1689. @property
  1690. def extra_select(self):
  1691. if self._extra_select_cache is not None:
  1692. return self._extra_select_cache
  1693. if not self._extra:
  1694. return {}
  1695. elif self.extra_select_mask is not None:
  1696. self._extra_select_cache = OrderedDict(
  1697. (k, v) for k, v in self.extra.items()
  1698. if k in self.extra_select_mask
  1699. )
  1700. return self._extra_select_cache
  1701. else:
  1702. return self.extra
  1703. def trim_start(self, names_with_path):
  1704. """
  1705. Trims joins from the start of the join path. The candidates for trim
  1706. are the PathInfos in names_with_path structure that are m2m joins.
  1707. Also sets the select column so the start matches the join.
  1708. This method is meant to be used for generating the subquery joins &
  1709. cols in split_exclude().
  1710. Returns a lookup usable for doing outerq.filter(lookup=self). Returns
  1711. also if the joins in the prefix contain a LEFT OUTER join.
  1712. _"""
  1713. all_paths = []
  1714. for _, paths in names_with_path:
  1715. all_paths.extend(paths)
  1716. contains_louter = False
  1717. # Trim and operate only on tables that were generated for
  1718. # the lookup part of the query. That is, avoid trimming
  1719. # joins generated for F() expressions.
  1720. lookup_tables = [t for t in self.tables if t in self._lookup_joins or t == self.tables[0]]
  1721. for trimmed_paths, path in enumerate(all_paths):
  1722. if path.m2m:
  1723. break
  1724. if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == self.LOUTER:
  1725. contains_louter = True
  1726. self.unref_alias(lookup_tables[trimmed_paths])
  1727. # The path.join_field is a Rel, lets get the other side's field
  1728. join_field = path.join_field.field
  1729. # Build the filter prefix.
  1730. paths_in_prefix = trimmed_paths
  1731. trimmed_prefix = []
  1732. for name, path in names_with_path:
  1733. if paths_in_prefix - len(path) < 0:
  1734. break
  1735. trimmed_prefix.append(name)
  1736. paths_in_prefix -= len(path)
  1737. trimmed_prefix.append(
  1738. join_field.foreign_related_fields[0].name)
  1739. trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)
  1740. # Lets still see if we can trim the first join from the inner query
  1741. # (that is, self). We can't do this for LEFT JOINs because we would
  1742. # miss those rows that have nothing on the outer side.
  1743. if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type != self.LOUTER:
  1744. select_fields = [r[0] for r in join_field.related_fields]
  1745. select_alias = lookup_tables[trimmed_paths + 1]
  1746. self.unref_alias(lookup_tables[trimmed_paths])
  1747. extra_restriction = join_field.get_extra_restriction(
  1748. self.where_class, None, lookup_tables[trimmed_paths + 1])
  1749. if extra_restriction:
  1750. self.where.add(extra_restriction, AND)
  1751. else:
  1752. # TODO: It might be possible to trim more joins from the start of the
  1753. # inner query if it happens to have a longer join chain containing the
  1754. # values in select_fields. Lets punt this one for now.
  1755. select_fields = [r[1] for r in join_field.related_fields]
  1756. select_alias = lookup_tables[trimmed_paths]
  1757. self.select = [SelectInfo((select_alias, f.column), f) for f in select_fields]
  1758. return trimmed_prefix, contains_louter
  1759. def is_nullable(self, field):
  1760. """
  1761. A helper to check if the given field should be treated as nullable.
  1762. Some backends treat '' as null and Django treats such fields as
  1763. nullable for those backends. In such situations field.null can be
  1764. False even if we should treat the field as nullable.
  1765. """
  1766. # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
  1767. # (nor should it have) knowledge of which connection is going to be
  1768. # used. The proper fix would be to defer all decisions where
  1769. # is_nullable() is needed to the compiler stage, but that is not easy
  1770. # to do currently.
  1771. if ((connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls)
  1772. and field.empty_strings_allowed):
  1773. return True
  1774. else:
  1775. return field.null
  1776. def get_order_dir(field, default='ASC'):
  1777. """
  1778. Returns the field name and direction for an order specification. For
  1779. example, '-foo' is returned as ('foo', 'DESC').
  1780. The 'default' param is used to indicate which way no prefix (or a '+'
  1781. prefix) should sort. The '-' prefix always sorts the opposite way.
  1782. """
  1783. dirn = ORDER_DIR[default]
  1784. if field[0] == '-':
  1785. return field[1:], dirn[1]
  1786. return field, dirn[0]
  1787. def add_to_dict(data, key, value):
  1788. """
  1789. A helper function to add "value" to the set of values for "key", whether or
  1790. not "key" already exists.
  1791. """
  1792. if key in data:
  1793. data[key].add(value)
  1794. else:
  1795. data[key] = set([value])
  1796. def is_reverse_o2o(field):
  1797. """
  1798. A little helper to check if the given field is reverse-o2o. The field is
  1799. expected to be some sort of relation field or related object.
  1800. """
  1801. return not hasattr(field, 'rel') and field.field.unique
  1802. def alias_diff(refcounts_before, refcounts_after):
  1803. """
  1804. Given the before and after copies of refcounts works out which aliases
  1805. have been added to the after copy.
  1806. """
  1807. # Use -1 as default value so that any join that is created, then trimmed
  1808. # is seen as added.
  1809. return set(t for t in refcounts_after
  1810. if refcounts_after[t] > refcounts_before.get(t, -1))
  1811. class JoinPromoter(object):
  1812. """
  1813. A class to abstract away join promotion problems for complex filter
  1814. conditions.
  1815. """
  1816. def __init__(self, connector, num_children, negated):
  1817. self.connector = connector
  1818. self.negated = negated
  1819. if self.negated:
  1820. if connector == AND:
  1821. self.effective_connector = OR
  1822. else:
  1823. self.effective_connector = AND
  1824. else:
  1825. self.effective_connector = self.connector
  1826. self.num_children = num_children
  1827. # Maps of table alias to how many times it is seen as required for
  1828. # inner and/or outer joins.
  1829. self.outer_votes = {}
  1830. self.inner_votes = {}
  1831. def add_votes(self, inner_votes):
  1832. """
  1833. Add single vote per item to self.inner_votes. Parameter can be any
  1834. iterable.
  1835. """
  1836. for voted in inner_votes:
  1837. self.inner_votes[voted] = self.inner_votes.get(voted, 0) + 1
  1838. def update_join_types(self, query):
  1839. """
  1840. Change join types so that the generated query is as efficient as
  1841. possible, but still correct. So, change as many joins as possible
  1842. to INNER, but don't make OUTER joins INNER if that could remove
  1843. results from the query.
  1844. """
  1845. to_promote = set()
  1846. to_demote = set()
  1847. # The effective_connector is used so that NOT (a AND b) is treated
  1848. # similarly to (a OR b) for join promotion.
  1849. for table, votes in self.inner_votes.items():
  1850. # We must use outer joins in OR case when the join isn't contained
  1851. # in all of the joins. Otherwise the INNER JOIN itself could remove
  1852. # valid results. Consider the case where a model with rel_a and
  1853. # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now,
  1854. # if rel_a join doesn't produce any results is null (for example
  1855. # reverse foreign key or null value in direct foreign key), and
  1856. # there is a matching row in rel_b with col=2, then an INNER join
  1857. # to rel_a would remove a valid match from the query. So, we need
  1858. # to promote any existing INNER to LOUTER (it is possible this
  1859. # promotion in turn will be demoted later on).
  1860. if self.effective_connector == 'OR' and votes < self.num_children:
  1861. to_promote.add(table)
  1862. # If connector is AND and there is a filter that can match only
  1863. # when there is a joinable row, then use INNER. For example, in
  1864. # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL
  1865. # as join output, then the col=1 or col=2 can't match (as
  1866. # NULL=anything is always false).
  1867. # For the OR case, if all children voted for a join to be inner,
  1868. # then we can use INNER for the join. For example:
  1869. # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell)
  1870. # then if rel_a doesn't produce any rows, the whole condition
  1871. # can't match. Hence we can safely use INNER join.
  1872. if self.effective_connector == 'AND' or (
  1873. self.effective_connector == 'OR' and votes == self.num_children):
  1874. to_demote.add(table)
  1875. # Finally, what happens in cases where we have:
  1876. # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0
  1877. # Now, we first generate the OR clause, and promote joins for it
  1878. # in the first if branch above. Both rel_a and rel_b are promoted
  1879. # to LOUTER joins. After that we do the AND case. The OR case
  1880. # voted no inner joins but the rel_a__col__gte=0 votes inner join
  1881. # for rel_a. We demote it back to INNER join (in AND case a single
  1882. # vote is enough). The demotion is OK, if rel_a doesn't produce
  1883. # rows, then the rel_a__col__gte=0 clause can't be true, and thus
  1884. # the whole clause must be false. So, it is safe to use INNER
  1885. # join.
  1886. # Note that in this example we could just as well have the __gte
  1887. # clause and the OR clause swapped. Or we could replace the __gte
  1888. # clause with an OR clause containing rel_a__col=1|rel_a__col=2,
  1889. # and again we could safely demote to INNER.
  1890. query.promote_joins(to_promote)
  1891. query.demote_joins(to_demote)
  1892. return to_demote