query.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030
  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 copy import deepcopy
  9. from django.utils.tree import Node
  10. from django.utils.datastructures import SortedDict
  11. from django.utils.encoding import force_unicode
  12. from django.db.backends.util import truncate_name
  13. from django.db import connection
  14. from django.db.models import signals
  15. from django.db.models.fields import FieldDoesNotExist
  16. from django.db.models.query_utils import select_related_descend
  17. from django.db.models.sql import aggregates as base_aggregates_module
  18. from django.db.models.sql.where import WhereNode, Constraint, EverythingNode, AND, OR
  19. from django.core.exceptions import FieldError
  20. from datastructures import EmptyResultSet, Empty, MultiJoin
  21. from constants import *
  22. try:
  23. set
  24. except NameError:
  25. from sets import Set as set # Python 2.3 fallback
  26. __all__ = ['Query', 'BaseQuery']
  27. class BaseQuery(object):
  28. """
  29. A single SQL query.
  30. """
  31. # SQL join types. These are part of the class because their string forms
  32. # vary from database to database and can be customised by a subclass.
  33. INNER = 'INNER JOIN'
  34. LOUTER = 'LEFT OUTER JOIN'
  35. alias_prefix = 'T'
  36. query_terms = QUERY_TERMS
  37. aggregates_module = base_aggregates_module
  38. def __init__(self, model, connection, where=WhereNode):
  39. self.model = model
  40. self.connection = connection
  41. self.alias_refcount = {}
  42. self.alias_map = {} # Maps alias to join information
  43. self.table_map = {} # Maps table names to list of aliases.
  44. self.join_map = {}
  45. self.rev_join_map = {} # Reverse of join_map.
  46. self.quote_cache = {}
  47. self.default_cols = True
  48. self.default_ordering = True
  49. self.standard_ordering = True
  50. self.ordering_aliases = []
  51. self.select_fields = []
  52. self.related_select_fields = []
  53. self.dupe_avoidance = {}
  54. self.used_aliases = set()
  55. self.filter_is_sticky = False
  56. # SQL-related attributes
  57. self.select = []
  58. self.tables = [] # Aliases in the order they are created.
  59. self.where = where()
  60. self.where_class = where
  61. self.group_by = []
  62. self.having = where()
  63. self.order_by = []
  64. self.low_mark, self.high_mark = 0, None # Used for offset/limit
  65. self.distinct = False
  66. self.select_related = False
  67. self.related_select_cols = []
  68. # SQL aggregate-related attributes
  69. self.aggregate_select = SortedDict() # Maps alias -> SQL aggregate function
  70. # Arbitrary maximum limit for select_related. Prevents infinite
  71. # recursion. Can be changed by the depth parameter to select_related().
  72. self.max_depth = 5
  73. # These are for extensions. The contents are more or less appended
  74. # verbatim to the appropriate clause.
  75. self.extra_select = SortedDict() # Maps col_alias -> (col_sql, params).
  76. self.extra_tables = ()
  77. self.extra_where = ()
  78. self.extra_params = ()
  79. self.extra_order_by = ()
  80. def __str__(self):
  81. """
  82. Returns the query as a string of SQL with the parameter values
  83. substituted in.
  84. Parameter values won't necessarily be quoted correctly, since that is
  85. done by the database interface at execution time.
  86. """
  87. sql, params = self.as_sql()
  88. return sql % params
  89. def __deepcopy__(self, memo):
  90. result= self.clone()
  91. memo[id(self)] = result
  92. return result
  93. def __getstate__(self):
  94. """
  95. Pickling support.
  96. """
  97. obj_dict = self.__dict__.copy()
  98. obj_dict['related_select_fields'] = []
  99. obj_dict['related_select_cols'] = []
  100. del obj_dict['connection']
  101. return obj_dict
  102. def __setstate__(self, obj_dict):
  103. """
  104. Unpickling support.
  105. """
  106. self.__dict__.update(obj_dict)
  107. # XXX: Need a better solution for this when multi-db stuff is
  108. # supported. It's the only class-reference to the module-level
  109. # connection variable.
  110. self.connection = connection
  111. def get_meta(self):
  112. """
  113. Returns the Options instance (the model._meta) from which to start
  114. processing. Normally, this is self.model._meta, but it can be changed
  115. by subclasses.
  116. """
  117. return self.model._meta
  118. def quote_name_unless_alias(self, name):
  119. """
  120. A wrapper around connection.ops.quote_name that doesn't quote aliases
  121. for table names. This avoids problems with some SQL dialects that treat
  122. quoted strings specially (e.g. PostgreSQL).
  123. """
  124. if name in self.quote_cache:
  125. return self.quote_cache[name]
  126. if ((name in self.alias_map and name not in self.table_map) or
  127. name in self.extra_select):
  128. self.quote_cache[name] = name
  129. return name
  130. r = self.connection.ops.quote_name(name)
  131. self.quote_cache[name] = r
  132. return r
  133. def clone(self, klass=None, **kwargs):
  134. """
  135. Creates a copy of the current instance. The 'kwargs' parameter can be
  136. used by clients to update attributes after copying has taken place.
  137. """
  138. obj = Empty()
  139. obj.__class__ = klass or self.__class__
  140. obj.model = self.model
  141. obj.connection = self.connection
  142. obj.alias_refcount = self.alias_refcount.copy()
  143. obj.alias_map = self.alias_map.copy()
  144. obj.table_map = self.table_map.copy()
  145. obj.join_map = self.join_map.copy()
  146. obj.rev_join_map = self.rev_join_map.copy()
  147. obj.quote_cache = {}
  148. obj.default_cols = self.default_cols
  149. obj.default_ordering = self.default_ordering
  150. obj.standard_ordering = self.standard_ordering
  151. obj.ordering_aliases = []
  152. obj.select_fields = self.select_fields[:]
  153. obj.related_select_fields = self.related_select_fields[:]
  154. obj.dupe_avoidance = self.dupe_avoidance.copy()
  155. obj.select = self.select[:]
  156. obj.tables = self.tables[:]
  157. obj.where = deepcopy(self.where)
  158. obj.where_class = self.where_class
  159. obj.group_by = self.group_by[:]
  160. obj.having = deepcopy(self.having)
  161. obj.order_by = self.order_by[:]
  162. obj.low_mark, obj.high_mark = self.low_mark, self.high_mark
  163. obj.distinct = self.distinct
  164. obj.select_related = self.select_related
  165. obj.related_select_cols = []
  166. obj.aggregate_select = self.aggregate_select.copy()
  167. obj.max_depth = self.max_depth
  168. obj.extra_select = self.extra_select.copy()
  169. obj.extra_tables = self.extra_tables
  170. obj.extra_where = self.extra_where
  171. obj.extra_params = self.extra_params
  172. obj.extra_order_by = self.extra_order_by
  173. if self.filter_is_sticky and self.used_aliases:
  174. obj.used_aliases = self.used_aliases.copy()
  175. else:
  176. obj.used_aliases = set()
  177. obj.filter_is_sticky = False
  178. obj.__dict__.update(kwargs)
  179. if hasattr(obj, '_setup_query'):
  180. obj._setup_query()
  181. return obj
  182. def convert_values(self, value, field):
  183. """Convert the database-returned value into a type that is consistent
  184. across database backends.
  185. By default, this defers to the underlying backend operations, but
  186. it can be overridden by Query classes for specific backends.
  187. """
  188. return self.connection.ops.convert_values(value, field)
  189. def resolve_aggregate(self, value, aggregate):
  190. """Resolve the value of aggregates returned by the database to
  191. consistent (and reasonable) types.
  192. This is required because of the predisposition of certain backends
  193. to return Decimal and long types when they are not needed.
  194. """
  195. if value is None:
  196. if aggregate.is_ordinal:
  197. return 0
  198. # Return None as-is
  199. return value
  200. elif aggregate.is_ordinal:
  201. # Any ordinal aggregate (e.g., count) returns an int
  202. return int(value)
  203. elif aggregate.is_computed:
  204. # Any computed aggregate (e.g., avg) returns a float
  205. return float(value)
  206. else:
  207. # Return value depends on the type of the field being processed.
  208. return self.convert_values(value, aggregate.field)
  209. def results_iter(self):
  210. """
  211. Returns an iterator over the results from executing this query.
  212. """
  213. resolve_columns = hasattr(self, 'resolve_columns')
  214. fields = None
  215. for rows in self.execute_sql(MULTI):
  216. for row in rows:
  217. if resolve_columns:
  218. if fields is None:
  219. # We only set this up here because
  220. # related_select_fields isn't populated until
  221. # execute_sql() has been called.
  222. if self.select_fields:
  223. fields = self.select_fields + self.related_select_fields
  224. else:
  225. fields = self.model._meta.fields
  226. row = self.resolve_columns(row, fields)
  227. if self.aggregate_select:
  228. aggregate_start = len(self.extra_select.keys()) + len(self.select)
  229. aggregate_end = aggregate_start + len(self.aggregate_select)
  230. row = tuple(row[:aggregate_start]) + tuple([
  231. self.resolve_aggregate(value, aggregate)
  232. for (alias, aggregate), value
  233. in zip(self.aggregate_select.items(), row[aggregate_start:aggregate_end])
  234. ]) + tuple(row[aggregate_end:])
  235. yield row
  236. def get_aggregation(self):
  237. """
  238. Returns the dictionary with the values of the existing aggregations.
  239. """
  240. if not self.aggregate_select:
  241. return {}
  242. # If there is a group by clause, aggregating does not add useful
  243. # information but retrieves only the first row. Aggregate
  244. # over the subquery instead.
  245. if self.group_by:
  246. from subqueries import AggregateQuery
  247. query = AggregateQuery(self.model, self.connection)
  248. obj = self.clone()
  249. # Remove any aggregates marked for reduction from the subquery
  250. # and move them to the outer AggregateQuery.
  251. for alias, aggregate in self.aggregate_select.items():
  252. if aggregate.is_summary:
  253. query.aggregate_select[alias] = aggregate
  254. del obj.aggregate_select[alias]
  255. query.add_subquery(obj)
  256. else:
  257. query = self
  258. self.select = []
  259. self.default_cols = False
  260. self.extra_select = {}
  261. query.clear_ordering(True)
  262. query.clear_limits()
  263. query.select_related = False
  264. query.related_select_cols = []
  265. query.related_select_fields = []
  266. result = query.execute_sql(SINGLE)
  267. if result is None:
  268. result = [None for q in query.aggregate_select.items()]
  269. return dict([
  270. (alias, self.resolve_aggregate(val, aggregate))
  271. for (alias, aggregate), val
  272. in zip(query.aggregate_select.items(), result)
  273. ])
  274. def get_count(self):
  275. """
  276. Performs a COUNT() query using the current filter constraints.
  277. """
  278. obj = self.clone()
  279. if len(self.select) > 1:
  280. # If a select clause exists, then the query has already started to
  281. # specify the columns that are to be returned.
  282. # In this case, we need to use a subquery to evaluate the count.
  283. from subqueries import AggregateQuery
  284. subquery = obj
  285. subquery.clear_ordering(True)
  286. subquery.clear_limits()
  287. obj = AggregateQuery(obj.model, obj.connection)
  288. obj.add_subquery(subquery)
  289. obj.add_count_column()
  290. number = obj.get_aggregation()[None]
  291. # Apply offset and limit constraints manually, since using LIMIT/OFFSET
  292. # in SQL (in variants that provide them) doesn't change the COUNT
  293. # output.
  294. number = max(0, number - self.low_mark)
  295. if self.high_mark:
  296. number = min(number, self.high_mark - self.low_mark)
  297. return number
  298. def as_sql(self, with_limits=True, with_col_aliases=False):
  299. """
  300. Creates the SQL for this query. Returns the SQL string and list of
  301. parameters.
  302. If 'with_limits' is False, any limit/offset information is not included
  303. in the query.
  304. """
  305. self.pre_sql_setup()
  306. out_cols = self.get_columns(with_col_aliases)
  307. ordering, ordering_group_by = self.get_ordering()
  308. # This must come after 'select' and 'ordering' -- see docstring of
  309. # get_from_clause() for details.
  310. from_, f_params = self.get_from_clause()
  311. qn = self.quote_name_unless_alias
  312. where, w_params = self.where.as_sql(qn=qn)
  313. having, h_params = self.having.as_sql(qn=qn)
  314. params = []
  315. for val in self.extra_select.itervalues():
  316. params.extend(val[1])
  317. result = ['SELECT']
  318. if self.distinct:
  319. result.append('DISTINCT')
  320. result.append(', '.join(out_cols + self.ordering_aliases))
  321. result.append('FROM')
  322. result.extend(from_)
  323. params.extend(f_params)
  324. if where:
  325. result.append('WHERE %s' % where)
  326. params.extend(w_params)
  327. if self.extra_where:
  328. if not where:
  329. result.append('WHERE')
  330. else:
  331. result.append('AND')
  332. result.append(' AND '.join(self.extra_where))
  333. if self.group_by:
  334. grouping = self.get_grouping()
  335. if ordering:
  336. # If the backend can't group by PK (i.e., any database
  337. # other than MySQL), then any fields mentioned in the
  338. # ordering clause needs to be in the group by clause.
  339. if not self.connection.features.allows_group_by_pk:
  340. grouping.extend(ordering_group_by)
  341. else:
  342. ordering = self.connection.ops.force_no_ordering()
  343. result.append('GROUP BY %s' % ', '.join(grouping))
  344. if having:
  345. result.append('HAVING %s' % having)
  346. params.extend(h_params)
  347. if ordering:
  348. result.append('ORDER BY %s' % ', '.join(ordering))
  349. if with_limits:
  350. if self.high_mark is not None:
  351. result.append('LIMIT %d' % (self.high_mark - self.low_mark))
  352. if self.low_mark:
  353. if self.high_mark is None:
  354. val = self.connection.ops.no_limit_value()
  355. if val:
  356. result.append('LIMIT %d' % val)
  357. result.append('OFFSET %d' % self.low_mark)
  358. params.extend(self.extra_params)
  359. return ' '.join(result), tuple(params)
  360. def as_nested_sql(self):
  361. """
  362. Perform the same functionality as the as_sql() method, returning an
  363. SQL string and parameters. However, the alias prefixes are bumped
  364. beforehand (in a copy -- the current query isn't changed) and any
  365. ordering is removed.
  366. Used when nesting this query inside another.
  367. """
  368. obj = self.clone()
  369. obj.clear_ordering(True)
  370. obj.bump_prefix()
  371. return obj.as_sql()
  372. def combine(self, rhs, connector):
  373. """
  374. Merge the 'rhs' query into the current one (with any 'rhs' effects
  375. being applied *after* (that is, "to the right of") anything in the
  376. current query. 'rhs' is not modified during a call to this function.
  377. The 'connector' parameter describes how to connect filters from the
  378. 'rhs' query.
  379. """
  380. assert self.model == rhs.model, \
  381. "Cannot combine queries on two different base models."
  382. assert self.can_filter(), \
  383. "Cannot combine queries once a slice has been taken."
  384. assert self.distinct == rhs.distinct, \
  385. "Cannot combine a unique query with a non-unique query."
  386. # Work out how to relabel the rhs aliases, if necessary.
  387. change_map = {}
  388. used = set()
  389. conjunction = (connector == AND)
  390. first = True
  391. for alias in rhs.tables:
  392. if not rhs.alias_refcount[alias]:
  393. # An unused alias.
  394. continue
  395. promote = (rhs.alias_map[alias][JOIN_TYPE] == self.LOUTER)
  396. new_alias = self.join(rhs.rev_join_map[alias],
  397. (conjunction and not first), used, promote, not conjunction)
  398. used.add(new_alias)
  399. change_map[alias] = new_alias
  400. first = False
  401. # So that we don't exclude valid results in an "or" query combination,
  402. # the first join that is exclusive to the lhs (self) must be converted
  403. # to an outer join.
  404. if not conjunction:
  405. for alias in self.tables[1:]:
  406. if self.alias_refcount[alias] == 1:
  407. self.promote_alias(alias, True)
  408. break
  409. # Now relabel a copy of the rhs where-clause and add it to the current
  410. # one.
  411. if rhs.where:
  412. w = deepcopy(rhs.where)
  413. w.relabel_aliases(change_map)
  414. if not self.where:
  415. # Since 'self' matches everything, add an explicit "include
  416. # everything" where-constraint so that connections between the
  417. # where clauses won't exclude valid results.
  418. self.where.add(EverythingNode(), AND)
  419. elif self.where:
  420. # rhs has an empty where clause.
  421. w = self.where_class()
  422. w.add(EverythingNode(), AND)
  423. else:
  424. w = self.where_class()
  425. self.where.add(w, connector)
  426. # Selection columns and extra extensions are those provided by 'rhs'.
  427. self.select = []
  428. for col in rhs.select:
  429. if isinstance(col, (list, tuple)):
  430. self.select.append((change_map.get(col[0], col[0]), col[1]))
  431. else:
  432. item = deepcopy(col)
  433. item.relabel_aliases(change_map)
  434. self.select.append(item)
  435. self.select_fields = rhs.select_fields[:]
  436. if connector == OR:
  437. # It would be nice to be able to handle this, but the queries don't
  438. # really make sense (or return consistent value sets). Not worth
  439. # the extra complexity when you can write a real query instead.
  440. if self.extra_select and rhs.extra_select:
  441. raise ValueError("When merging querysets using 'or', you "
  442. "cannot have extra(select=...) on both sides.")
  443. if self.extra_where and rhs.extra_where:
  444. raise ValueError("When merging querysets using 'or', you "
  445. "cannot have extra(where=...) on both sides.")
  446. self.extra_select.update(rhs.extra_select)
  447. self.extra_tables += rhs.extra_tables
  448. self.extra_where += rhs.extra_where
  449. self.extra_params += rhs.extra_params
  450. # Ordering uses the 'rhs' ordering, unless it has none, in which case
  451. # the current ordering is used.
  452. self.order_by = rhs.order_by and rhs.order_by[:] or self.order_by
  453. self.extra_order_by = rhs.extra_order_by or self.extra_order_by
  454. def pre_sql_setup(self):
  455. """
  456. Does any necessary class setup immediately prior to producing SQL. This
  457. is for things that can't necessarily be done in __init__ because we
  458. might not have all the pieces in place at that time.
  459. """
  460. if not self.tables:
  461. self.join((None, self.model._meta.db_table, None, None))
  462. if self.select_related and not self.related_select_cols:
  463. self.fill_related_selections()
  464. def get_columns(self, with_aliases=False):
  465. """
  466. Return the list of columns to use in the select statement. If no
  467. columns have been specified, returns all columns relating to fields in
  468. the model.
  469. If 'with_aliases' is true, any column names that are duplicated
  470. (without the table names) are given unique aliases. This is needed in
  471. some cases to avoid ambiguitity with nested queries.
  472. """
  473. qn = self.quote_name_unless_alias
  474. qn2 = self.connection.ops.quote_name
  475. result = ['(%s) AS %s' % (col[0], qn2(alias)) for alias, col in self.extra_select.iteritems()]
  476. aliases = set(self.extra_select.keys())
  477. if with_aliases:
  478. col_aliases = aliases.copy()
  479. else:
  480. col_aliases = set()
  481. if self.select:
  482. for col in self.select:
  483. if isinstance(col, (list, tuple)):
  484. r = '%s.%s' % (qn(col[0]), qn(col[1]))
  485. if with_aliases:
  486. if col[1] in col_aliases:
  487. c_alias = 'Col%d' % len(col_aliases)
  488. result.append('%s AS %s' % (r, c_alias))
  489. aliases.add(c_alias)
  490. col_aliases.add(c_alias)
  491. else:
  492. result.append('%s AS %s' % (r, col[1]))
  493. aliases.add(r)
  494. col_aliases.add(col[1])
  495. else:
  496. result.append(r)
  497. aliases.add(r)
  498. col_aliases.add(col[1])
  499. else:
  500. result.append(col.as_sql(quote_func=qn))
  501. if hasattr(col, 'alias'):
  502. aliases.add(col.alias)
  503. col_aliases.add(col.alias)
  504. elif self.default_cols:
  505. cols, new_aliases = self.get_default_columns(with_aliases,
  506. col_aliases)
  507. result.extend(cols)
  508. aliases.update(new_aliases)
  509. result.extend([
  510. '%s%s' % (
  511. aggregate.as_sql(quote_func=qn),
  512. alias is not None and ' AS %s' % qn(alias) or ''
  513. )
  514. for alias, aggregate in self.aggregate_select.items()
  515. ])
  516. for table, col in self.related_select_cols:
  517. r = '%s.%s' % (qn(table), qn(col))
  518. if with_aliases and col in col_aliases:
  519. c_alias = 'Col%d' % len(col_aliases)
  520. result.append('%s AS %s' % (r, c_alias))
  521. aliases.add(c_alias)
  522. col_aliases.add(c_alias)
  523. else:
  524. result.append(r)
  525. aliases.add(r)
  526. col_aliases.add(col)
  527. self._select_aliases = aliases
  528. return result
  529. def get_default_columns(self, with_aliases=False, col_aliases=None,
  530. start_alias=None, opts=None, as_pairs=False):
  531. """
  532. Computes the default columns for selecting every field in the base
  533. model.
  534. Returns a list of strings, quoted appropriately for use in SQL
  535. directly, as well as a set of aliases used in the select statement (if
  536. 'as_pairs' is True, returns a list of (alias, col_name) pairs instead
  537. of strings as the first component and None as the second component).
  538. """
  539. result = []
  540. if opts is None:
  541. opts = self.model._meta
  542. if start_alias:
  543. table_alias = start_alias
  544. else:
  545. table_alias = self.tables[0]
  546. root_pk = opts.pk.column
  547. seen = {None: table_alias}
  548. qn = self.quote_name_unless_alias
  549. qn2 = self.connection.ops.quote_name
  550. aliases = set()
  551. for field, model in opts.get_fields_with_model():
  552. try:
  553. alias = seen[model]
  554. except KeyError:
  555. alias = self.join((table_alias, model._meta.db_table,
  556. root_pk, model._meta.pk.column))
  557. seen[model] = alias
  558. if as_pairs:
  559. result.append((alias, field.column))
  560. continue
  561. if with_aliases and field.column in col_aliases:
  562. c_alias = 'Col%d' % len(col_aliases)
  563. result.append('%s.%s AS %s' % (qn(alias),
  564. qn2(field.column), c_alias))
  565. col_aliases.add(c_alias)
  566. aliases.add(c_alias)
  567. else:
  568. r = '%s.%s' % (qn(alias), qn2(field.column))
  569. result.append(r)
  570. aliases.add(r)
  571. if with_aliases:
  572. col_aliases.add(field.column)
  573. if as_pairs:
  574. return result, None
  575. return result, aliases
  576. def get_from_clause(self):
  577. """
  578. Returns a list of strings that are joined together to go after the
  579. "FROM" part of the query, as well as a list any extra parameters that
  580. need to be included. Sub-classes, can override this to create a
  581. from-clause via a "select".
  582. This should only be called after any SQL construction methods that
  583. might change the tables we need. This means the select columns and
  584. ordering must be done first.
  585. """
  586. result = []
  587. qn = self.quote_name_unless_alias
  588. qn2 = self.connection.ops.quote_name
  589. first = True
  590. for alias in self.tables:
  591. if not self.alias_refcount[alias]:
  592. continue
  593. try:
  594. name, alias, join_type, lhs, lhs_col, col, nullable = self.alias_map[alias]
  595. except KeyError:
  596. # Extra tables can end up in self.tables, but not in the
  597. # alias_map if they aren't in a join. That's OK. We skip them.
  598. continue
  599. alias_str = (alias != name and ' %s' % alias or '')
  600. if join_type and not first:
  601. result.append('%s %s%s ON (%s.%s = %s.%s)'
  602. % (join_type, qn(name), alias_str, qn(lhs),
  603. qn2(lhs_col), qn(alias), qn2(col)))
  604. else:
  605. connector = not first and ', ' or ''
  606. result.append('%s%s%s' % (connector, qn(name), alias_str))
  607. first = False
  608. for t in self.extra_tables:
  609. alias, unused = self.table_alias(t)
  610. # Only add the alias if it's not already present (the table_alias()
  611. # calls increments the refcount, so an alias refcount of one means
  612. # this is the only reference.
  613. if alias not in self.alias_map or self.alias_refcount[alias] == 1:
  614. connector = not first and ', ' or ''
  615. result.append('%s%s' % (connector, qn(alias)))
  616. first = False
  617. return result, []
  618. def get_grouping(self):
  619. """
  620. Returns a tuple representing the SQL elements in the "group by" clause.
  621. """
  622. qn = self.quote_name_unless_alias
  623. result = []
  624. for col in self.group_by:
  625. if isinstance(col, (list, tuple)):
  626. result.append('%s.%s' % (qn(col[0]), qn(col[1])))
  627. elif hasattr(col, 'as_sql'):
  628. result.append(col.as_sql(qn))
  629. else:
  630. result.append(str(col))
  631. return result
  632. def get_ordering(self):
  633. """
  634. Returns a tuple containing a list representing the SQL elements in the
  635. "order by" clause, and the list of SQL elements that need to be added
  636. to the GROUP BY clause as a result of the ordering.
  637. Also sets the ordering_aliases attribute on this instance to a list of
  638. extra aliases needed in the select.
  639. Determining the ordering SQL can change the tables we need to include,
  640. so this should be run *before* get_from_clause().
  641. """
  642. if self.extra_order_by:
  643. ordering = self.extra_order_by
  644. elif not self.default_ordering:
  645. ordering = self.order_by
  646. else:
  647. ordering = self.order_by or self.model._meta.ordering
  648. qn = self.quote_name_unless_alias
  649. qn2 = self.connection.ops.quote_name
  650. distinct = self.distinct
  651. select_aliases = self._select_aliases
  652. result = []
  653. group_by = []
  654. ordering_aliases = []
  655. if self.standard_ordering:
  656. asc, desc = ORDER_DIR['ASC']
  657. else:
  658. asc, desc = ORDER_DIR['DESC']
  659. # It's possible, due to model inheritance, that normal usage might try
  660. # to include the same field more than once in the ordering. We track
  661. # the table/column pairs we use and discard any after the first use.
  662. processed_pairs = set()
  663. for field in ordering:
  664. if field == '?':
  665. result.append(self.connection.ops.random_function_sql())
  666. continue
  667. if isinstance(field, int):
  668. if field < 0:
  669. order = desc
  670. field = -field
  671. else:
  672. order = asc
  673. result.append('%s %s' % (field, order))
  674. group_by.append(field)
  675. continue
  676. col, order = get_order_dir(field, asc)
  677. if col in self.aggregate_select:
  678. result.append('%s %s' % (col, order))
  679. continue
  680. if '.' in field:
  681. # This came in through an extra(order_by=...) addition. Pass it
  682. # on verbatim.
  683. table, col = col.split('.', 1)
  684. if (table, col) not in processed_pairs:
  685. elt = '%s.%s' % (qn(table), col)
  686. processed_pairs.add((table, col))
  687. if not distinct or elt in select_aliases:
  688. result.append('%s %s' % (elt, order))
  689. group_by.append(elt)
  690. elif get_order_dir(field)[0] not in self.extra_select:
  691. # 'col' is of the form 'field' or 'field1__field2' or
  692. # '-field1__field2__field', etc.
  693. for table, col, order in self.find_ordering_name(field,
  694. self.model._meta, default_order=asc):
  695. if (table, col) not in processed_pairs:
  696. elt = '%s.%s' % (qn(table), qn2(col))
  697. processed_pairs.add((table, col))
  698. if distinct and elt not in select_aliases:
  699. ordering_aliases.append(elt)
  700. result.append('%s %s' % (elt, order))
  701. group_by.append(elt)
  702. else:
  703. elt = qn2(col)
  704. if distinct and col not in select_aliases:
  705. ordering_aliases.append(elt)
  706. result.append('%s %s' % (elt, order))
  707. group_by.append(elt)
  708. self.ordering_aliases = ordering_aliases
  709. return result, group_by
  710. def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
  711. already_seen=None):
  712. """
  713. Returns the table alias (the name might be ambiguous, the alias will
  714. not be) and column name for ordering by the given 'name' parameter.
  715. The 'name' is of the form 'field1__field2__...__fieldN'.
  716. """
  717. name, order = get_order_dir(name, default_order)
  718. pieces = name.split(LOOKUP_SEP)
  719. if not alias:
  720. alias = self.get_initial_alias()
  721. field, target, opts, joins, last, extra = self.setup_joins(pieces,
  722. opts, alias, False)
  723. alias = joins[-1]
  724. col = target.column
  725. if not field.rel:
  726. # To avoid inadvertent trimming of a necessary alias, use the
  727. # refcount to show that we are referencing a non-relation field on
  728. # the model.
  729. self.ref_alias(alias)
  730. # Must use left outer joins for nullable fields.
  731. self.promote_alias_chain(joins)
  732. # If we get to this point and the field is a relation to another model,
  733. # append the default ordering for that model.
  734. if field.rel and len(joins) > 1 and opts.ordering:
  735. # Firstly, avoid infinite loops.
  736. if not already_seen:
  737. already_seen = set()
  738. join_tuple = tuple([self.alias_map[j][TABLE_NAME] for j in joins])
  739. if join_tuple in already_seen:
  740. raise FieldError('Infinite loop caused by ordering.')
  741. already_seen.add(join_tuple)
  742. results = []
  743. for item in opts.ordering:
  744. results.extend(self.find_ordering_name(item, opts, alias,
  745. order, already_seen))
  746. return results
  747. if alias:
  748. # We have to do the same "final join" optimisation as in
  749. # add_filter, since the final column might not otherwise be part of
  750. # the select set (so we can't order on it).
  751. while 1:
  752. join = self.alias_map[alias]
  753. if col != join[RHS_JOIN_COL]:
  754. break
  755. self.unref_alias(alias)
  756. alias = join[LHS_ALIAS]
  757. col = join[LHS_JOIN_COL]
  758. return [(alias, col, order)]
  759. def table_alias(self, table_name, create=False):
  760. """
  761. Returns a table alias for the given table_name and whether this is a
  762. new alias or not.
  763. If 'create' is true, a new alias is always created. Otherwise, the
  764. most recently created alias for the table (if one exists) is reused.
  765. """
  766. current = self.table_map.get(table_name)
  767. if not create and current:
  768. alias = current[0]
  769. self.alias_refcount[alias] += 1
  770. return alias, False
  771. # Create a new alias for this table.
  772. if current:
  773. alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 1)
  774. current.append(alias)
  775. else:
  776. # The first occurence of a table uses the table name directly.
  777. alias = table_name
  778. self.table_map[alias] = [alias]
  779. self.alias_refcount[alias] = 1
  780. self.tables.append(alias)
  781. return alias, True
  782. def ref_alias(self, alias):
  783. """ Increases the reference count for this alias. """
  784. self.alias_refcount[alias] += 1
  785. def unref_alias(self, alias):
  786. """ Decreases the reference count for this alias. """
  787. self.alias_refcount[alias] -= 1
  788. def promote_alias(self, alias, unconditional=False):
  789. """
  790. Promotes the join type of an alias to an outer join if it's possible
  791. for the join to contain NULL values on the left. If 'unconditional' is
  792. False, the join is only promoted if it is nullable, otherwise it is
  793. always promoted.
  794. Returns True if the join was promoted.
  795. """
  796. if ((unconditional or self.alias_map[alias][NULLABLE]) and
  797. self.alias_map[alias][JOIN_TYPE] != self.LOUTER):
  798. data = list(self.alias_map[alias])
  799. data[JOIN_TYPE] = self.LOUTER
  800. self.alias_map[alias] = tuple(data)
  801. return True
  802. return False
  803. def promote_alias_chain(self, chain, must_promote=False):
  804. """
  805. Walks along a chain of aliases, promoting the first nullable join and
  806. any joins following that. If 'must_promote' is True, all the aliases in
  807. the chain are promoted.
  808. """
  809. for alias in chain:
  810. if self.promote_alias(alias, must_promote):
  811. must_promote = True
  812. def promote_unused_aliases(self, initial_refcounts, used_aliases):
  813. """
  814. Given a "before" copy of the alias_refcounts dictionary (as
  815. 'initial_refcounts') and a collection of aliases that may have been
  816. changed or created, works out which aliases have been created since
  817. then and which ones haven't been used and promotes all of those
  818. aliases, plus any children of theirs in the alias tree, to outer joins.
  819. """
  820. # FIXME: There's some (a lot of!) overlap with the similar OR promotion
  821. # in add_filter(). It's not quite identical, but is very similar. So
  822. # pulling out the common bits is something for later.
  823. considered = {}
  824. for alias in self.tables:
  825. if alias not in used_aliases:
  826. continue
  827. if (alias not in initial_refcounts or
  828. self.alias_refcount[alias] == initial_refcounts[alias]):
  829. parent = self.alias_map[alias][LHS_ALIAS]
  830. must_promote = considered.get(parent, False)
  831. promoted = self.promote_alias(alias, must_promote)
  832. considered[alias] = must_promote or promoted
  833. def change_aliases(self, change_map):
  834. """
  835. Changes the aliases in change_map (which maps old-alias -> new-alias),
  836. relabelling any references to them in select columns and the where
  837. clause.
  838. """
  839. assert set(change_map.keys()).intersection(set(change_map.values())) == set()
  840. # 1. Update references in "select" and "where".
  841. self.where.relabel_aliases(change_map)
  842. for pos, col in enumerate(self.select):
  843. if isinstance(col, (list, tuple)):
  844. old_alias = col[0]
  845. self.select[pos] = (change_map.get(old_alias, old_alias), col[1])
  846. else:
  847. col.relabel_aliases(change_map)
  848. # 2. Rename the alias in the internal table/alias datastructures.
  849. for old_alias, new_alias in change_map.iteritems():
  850. alias_data = list(self.alias_map[old_alias])
  851. alias_data[RHS_ALIAS] = new_alias
  852. t = self.rev_join_map[old_alias]
  853. data = list(self.join_map[t])
  854. data[data.index(old_alias)] = new_alias
  855. self.join_map[t] = tuple(data)
  856. self.rev_join_map[new_alias] = t
  857. del self.rev_join_map[old_alias]
  858. self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
  859. del self.alias_refcount[old_alias]
  860. self.alias_map[new_alias] = tuple(alias_data)
  861. del self.alias_map[old_alias]
  862. table_aliases = self.table_map[alias_data[TABLE_NAME]]
  863. for pos, alias in enumerate(table_aliases):
  864. if alias == old_alias:
  865. table_aliases[pos] = new_alias
  866. break
  867. for pos, alias in enumerate(self.tables):
  868. if alias == old_alias:
  869. self.tables[pos] = new_alias
  870. break
  871. # 3. Update any joins that refer to the old alias.
  872. for alias, data in self.alias_map.iteritems():
  873. lhs = data[LHS_ALIAS]
  874. if lhs in change_map:
  875. data = list(data)
  876. data[LHS_ALIAS] = change_map[lhs]
  877. self.alias_map[alias] = tuple(data)
  878. def bump_prefix(self, exceptions=()):
  879. """
  880. Changes the alias prefix to the next letter in the alphabet and
  881. relabels all the aliases. Even tables that previously had no alias will
  882. get an alias after this call (it's mostly used for nested queries and
  883. the outer query will already be using the non-aliased table name).
  884. Subclasses who create their own prefix should override this method to
  885. produce a similar result (a new prefix and relabelled aliases).
  886. The 'exceptions' parameter is a container that holds alias names which
  887. should not be changed.
  888. """
  889. current = ord(self.alias_prefix)
  890. assert current < ord('Z')
  891. prefix = chr(current + 1)
  892. self.alias_prefix = prefix
  893. change_map = {}
  894. for pos, alias in enumerate(self.tables):
  895. if alias in exceptions:
  896. continue
  897. new_alias = '%s%d' % (prefix, pos)
  898. change_map[alias] = new_alias
  899. self.tables[pos] = new_alias
  900. self.change_aliases(change_map)
  901. def get_initial_alias(self):
  902. """
  903. Returns the first alias for this query, after increasing its reference
  904. count.
  905. """
  906. if self.tables:
  907. alias = self.tables[0]
  908. self.ref_alias(alias)
  909. else:
  910. alias = self.join((None, self.model._meta.db_table, None, None))
  911. return alias
  912. def count_active_tables(self):
  913. """
  914. Returns the number of tables in this query with a non-zero reference
  915. count.
  916. """
  917. return len([1 for count in self.alias_refcount.itervalues() if count])
  918. def join(self, connection, always_create=False, exclusions=(),
  919. promote=False, outer_if_first=False, nullable=False, reuse=None):
  920. """
  921. Returns an alias for the join in 'connection', either reusing an
  922. existing alias for that join or creating a new one. 'connection' is a
  923. tuple (lhs, table, lhs_col, col) where 'lhs' is either an existing
  924. table alias or a table name. The join correspods to the SQL equivalent
  925. of::
  926. lhs.lhs_col = table.col
  927. If 'always_create' is True and 'reuse' is None, a new alias is always
  928. created, regardless of whether one already exists or not. Otherwise
  929. 'reuse' must be a set and a new join is created unless one of the
  930. aliases in `reuse` can be used.
  931. If 'exclusions' is specified, it is something satisfying the container
  932. protocol ("foo in exclusions" must work) and specifies a list of
  933. aliases that should not be returned, even if they satisfy the join.
  934. If 'promote' is True, the join type for the alias will be LOUTER (if
  935. the alias previously existed, the join type will be promoted from INNER
  936. to LOUTER, if necessary).
  937. If 'outer_if_first' is True and a new join is created, it will have the
  938. LOUTER join type. This is used when joining certain types of querysets
  939. and Q-objects together.
  940. If 'nullable' is True, the join can potentially involve NULL values and
  941. is a candidate for promotion (to "left outer") when combining querysets.
  942. """
  943. lhs, table, lhs_col, col = connection
  944. if lhs in self.alias_map:
  945. lhs_table = self.alias_map[lhs][TABLE_NAME]
  946. else:
  947. lhs_table = lhs
  948. if reuse and always_create and table in self.table_map:
  949. # Convert the 'reuse' to case to be "exclude everything but the
  950. # reusable set, minus exclusions, for this table".
  951. exclusions = set(self.table_map[table]).difference(reuse).union(set(exclusions))
  952. always_create = False
  953. t_ident = (lhs_table, table, lhs_col, col)
  954. if not always_create:
  955. for alias in self.join_map.get(t_ident, ()):
  956. if alias not in exclusions:
  957. if lhs_table and not self.alias_refcount[self.alias_map[alias][LHS_ALIAS]]:
  958. # The LHS of this join tuple is no longer part of the
  959. # query, so skip this possibility.
  960. continue
  961. if self.alias_map[alias][LHS_ALIAS] != lhs:
  962. continue
  963. self.ref_alias(alias)
  964. if promote:
  965. self.promote_alias(alias)
  966. return alias
  967. # No reuse is possible, so we need a new alias.
  968. alias, _ = self.table_alias(table, True)
  969. if not lhs:
  970. # Not all tables need to be joined to anything. No join type
  971. # means the later columns are ignored.
  972. join_type = None
  973. elif promote or outer_if_first:
  974. join_type = self.LOUTER
  975. else:
  976. join_type = self.INNER
  977. join = (table, alias, join_type, lhs, lhs_col, col, nullable)
  978. self.alias_map[alias] = join
  979. if t_ident in self.join_map:
  980. self.join_map[t_ident] += (alias,)
  981. else:
  982. self.join_map[t_ident] = (alias,)
  983. self.rev_join_map[alias] = t_ident
  984. return alias
  985. def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1,
  986. used=None, requested=None, restricted=None, nullable=None,
  987. dupe_set=None, avoid_set=None):
  988. """
  989. Fill in the information needed for a select_related query. The current
  990. depth is measured as the number of connections away from the root model
  991. (for example, cur_depth=1 means we are looking at models with direct
  992. connections to the root model).
  993. """
  994. if not restricted and self.max_depth and cur_depth > self.max_depth:
  995. # We've recursed far enough; bail out.
  996. return
  997. if not opts:
  998. opts = self.get_meta()
  999. root_alias = self.get_initial_alias()
  1000. self.related_select_cols = []
  1001. self.related_select_fields = []
  1002. if not used:
  1003. used = set()
  1004. if dupe_set is None:
  1005. dupe_set = set()
  1006. if avoid_set is None:
  1007. avoid_set = set()
  1008. orig_dupe_set = dupe_set
  1009. # Setup for the case when only particular related fields should be
  1010. # included in the related selection.
  1011. if requested is None and restricted is not False:
  1012. if isinstance(self.select_related, dict):
  1013. requested = self.select_related
  1014. restricted = True
  1015. else:
  1016. restricted = False
  1017. for f, model in opts.get_fields_with_model():
  1018. if not select_related_descend(f, restricted, requested):
  1019. continue
  1020. # The "avoid" set is aliases we want to avoid just for this
  1021. # particular branch of the recursion. They aren't permanently
  1022. # forbidden from reuse in the related selection tables (which is
  1023. # what "used" specifies).
  1024. avoid = avoid_set.copy()
  1025. dupe_set = orig_dupe_set.copy()
  1026. table = f.rel.to._meta.db_table
  1027. if nullable or f.null:
  1028. promote = True
  1029. else:
  1030. promote = False
  1031. if model:
  1032. int_opts = opts
  1033. alias = root_alias
  1034. for int_model in opts.get_base_chain(model):
  1035. lhs_col = int_opts.parents[int_model].column
  1036. dedupe = lhs_col in opts.duplicate_targets
  1037. if dedupe:
  1038. avoid.update(self.dupe_avoidance.get(id(opts), lhs_col),
  1039. ())
  1040. dupe_set.add((opts, lhs_col))
  1041. int_opts = int_model._meta
  1042. alias = self.join((alias, int_opts.db_table, lhs_col,
  1043. int_opts.pk.column), exclusions=used,
  1044. promote=promote)
  1045. for (dupe_opts, dupe_col) in dupe_set:
  1046. self.update_dupe_avoidance(dupe_opts, dupe_col, alias)
  1047. else:
  1048. alias = root_alias
  1049. dedupe = f.column in opts.duplicate_targets
  1050. if dupe_set or dedupe:
  1051. avoid.update(self.dupe_avoidance.get((id(opts), f.column), ()))
  1052. if dedupe:
  1053. dupe_set.add((opts, f.column))
  1054. alias = self.join((alias, table, f.column,
  1055. f.rel.get_related_field().column),
  1056. exclusions=used.union(avoid), promote=promote)
  1057. used.add(alias)
  1058. self.related_select_cols.extend(self.get_default_columns(
  1059. start_alias=alias, opts=f.rel.to._meta, as_pairs=True)[0])
  1060. self.related_select_fields.extend(f.rel.to._meta.fields)
  1061. if restricted:
  1062. next = requested.get(f.name, {})
  1063. else:
  1064. next = False
  1065. if f.null is not None:
  1066. new_nullable = f.null
  1067. else:
  1068. new_nullable = None
  1069. for dupe_opts, dupe_col in dupe_set:
  1070. self.update_dupe_avoidance(dupe_opts, dupe_col, alias)
  1071. self.fill_related_selections(f.rel.to._meta, alias, cur_depth + 1,
  1072. used, next, restricted, new_nullable, dupe_set, avoid)
  1073. def add_aggregate(self, aggregate, model, alias, is_summary):
  1074. """
  1075. Adds a single aggregate expression to the Query
  1076. """
  1077. opts = model._meta
  1078. field_list = aggregate.lookup.split(LOOKUP_SEP)
  1079. if (len(field_list) == 1 and
  1080. aggregate.lookup in self.aggregate_select.keys()):
  1081. # Aggregate is over an annotation
  1082. field_name = field_list[0]
  1083. col = field_name
  1084. source = self.aggregate_select[field_name]
  1085. elif (len(field_list) > 1 or
  1086. field_list[0] not in [i.name for i in opts.fields]):
  1087. field, source, opts, join_list, last, _ = self.setup_joins(
  1088. field_list, opts, self.get_initial_alias(), False)
  1089. # Process the join chain to see if it can be trimmed
  1090. _, _, col, _, join_list = self.trim_joins(source, join_list, last, False)
  1091. # If the aggregate references a model or field that requires a join,
  1092. # those joins must be LEFT OUTER - empty join rows must be returned
  1093. # in order for zeros to be returned for those aggregates.
  1094. for column_alias in join_list:
  1095. self.promote_alias(column_alias, unconditional=True)
  1096. col = (join_list[-1], col)
  1097. else:
  1098. # Aggregate references a normal field
  1099. field_name = field_list[0]
  1100. source = opts.get_field(field_name)
  1101. if not (self.group_by and is_summary):
  1102. # Only use a column alias if this is a
  1103. # standalone aggregate, or an annotation
  1104. col = (opts.db_table, source.column)
  1105. else:
  1106. col = field_name
  1107. # Add the aggregate to the query
  1108. alias = truncate_name(alias, self.connection.ops.max_name_length())
  1109. aggregate.add_to_query(self, alias, col=col, source=source, is_summary=is_summary)
  1110. def add_filter(self, filter_expr, connector=AND, negate=False, trim=False,
  1111. can_reuse=None, process_extras=True):
  1112. """
  1113. Add a single filter to the query. The 'filter_expr' is a pair:
  1114. (filter_string, value). E.g. ('name__contains', 'fred')
  1115. If 'negate' is True, this is an exclude() filter. It's important to
  1116. note that this method does not negate anything in the where-clause
  1117. object when inserting the filter constraints. This is because negated
  1118. filters often require multiple calls to add_filter() and the negation
  1119. should only happen once. So the caller is responsible for this (the
  1120. caller will normally be add_q(), so that as an example).
  1121. If 'trim' is True, we automatically trim the final join group (used
  1122. internally when constructing nested queries).
  1123. If 'can_reuse' is a set, we are processing a component of a
  1124. multi-component filter (e.g. filter(Q1, Q2)). In this case, 'can_reuse'
  1125. will be a set of table aliases that can be reused in this filter, even
  1126. if we would otherwise force the creation of new aliases for a join
  1127. (needed for nested Q-filters). The set is updated by this method.
  1128. If 'process_extras' is set, any extra filters returned from the table
  1129. joining process will be processed. This parameter is set to False
  1130. during the processing of extra filters to avoid infinite recursion.
  1131. """
  1132. arg, value = filter_expr
  1133. parts = arg.split(LOOKUP_SEP)
  1134. if not parts:
  1135. raise FieldError("Cannot parse keyword query %r" % arg)
  1136. # Work out the lookup type and remove it from 'parts', if necessary.
  1137. if len(parts) == 1 or parts[-1] not in self.query_terms:
  1138. lookup_type = 'exact'
  1139. else:
  1140. lookup_type = parts.pop()
  1141. # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
  1142. # uses of None as a query value.
  1143. if value is None:
  1144. if lookup_type != 'exact':
  1145. raise ValueError("Cannot use None as a query value")
  1146. lookup_type = 'isnull'
  1147. value = True
  1148. elif (value == '' and lookup_type == 'exact' and
  1149. connection.features.interprets_empty_strings_as_nulls):
  1150. lookup_type = 'isnull'
  1151. value = True
  1152. elif callable(value):
  1153. value = value()
  1154. for alias, aggregate in self.aggregate_select.items():
  1155. if alias == parts[0]:
  1156. entry = self.where_class()
  1157. entry.add((aggregate, lookup_type, value), AND)
  1158. if negate:
  1159. entry.negate()
  1160. self.having.add(entry, AND)
  1161. return
  1162. opts = self.get_meta()
  1163. alias = self.get_initial_alias()
  1164. allow_many = trim or not negate
  1165. try:
  1166. field, target, opts, join_list, last, extra_filters = self.setup_joins(
  1167. parts, opts, alias, True, allow_many, can_reuse=can_reuse,
  1168. negate=negate, process_extras=process_extras)
  1169. except MultiJoin, e:
  1170. self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
  1171. can_reuse)
  1172. return
  1173. # Process the join chain to see if it can be trimmed
  1174. final, penultimate, col, alias, join_list = self.trim_joins(target, join_list, last, trim)
  1175. if (lookup_type == 'isnull' and value is True and not negate and
  1176. final > 1):
  1177. # If the comparison is against NULL, we need to use a left outer
  1178. # join when connecting to the previous model. We make that
  1179. # adjustment here. We don't do this unless needed as it's less
  1180. # efficient at the database level.
  1181. self.promote_alias(join_list[penultimate])
  1182. if connector == OR:
  1183. # Some joins may need to be promoted when adding a new filter to a
  1184. # disjunction. We walk the list of new joins and where it diverges
  1185. # from any previous joins (ref count is 1 in the table list), we
  1186. # make the new additions (and any existing ones not used in the new
  1187. # join list) an outer join.
  1188. join_it = iter(join_list)
  1189. table_it = iter(self.tables)
  1190. join_it.next(), table_it.next()
  1191. table_promote = False
  1192. join_promote = False
  1193. for join in join_it:
  1194. table = table_it.next()
  1195. if join == table and self.alias_refcount[join] > 1:
  1196. continue
  1197. join_promote = self.promote_alias(join)
  1198. if table != join:
  1199. table_promote = self.promote_alias(table)
  1200. break
  1201. self.promote_alias_chain(join_it, join_promote)
  1202. self.promote_alias_chain(table_it, table_promote)
  1203. self.where.add((Constraint(alias, col, field), lookup_type, value),
  1204. connector)
  1205. if negate:
  1206. self.promote_alias_chain(join_list)
  1207. if lookup_type != 'isnull':
  1208. if final > 1:
  1209. for alias in join_list:
  1210. if self.alias_map[alias][JOIN_TYPE] == self.LOUTER:
  1211. j_col = self.alias_map[alias][RHS_JOIN_COL]
  1212. entry = self.where_class()
  1213. entry.add((Constraint(alias, j_col, None), 'isnull', True), AND)
  1214. entry.negate()
  1215. self.where.add(entry, AND)
  1216. break
  1217. elif not (lookup_type == 'in' and not value) and field.null:
  1218. # Leaky abstraction artifact: We have to specifically
  1219. # exclude the "foo__in=[]" case from this handling, because
  1220. # it's short-circuited in the Where class.
  1221. entry = self.where_class()
  1222. entry.add((Constraint(alias, col, None), 'isnull', True), AND)
  1223. entry.negate()
  1224. self.where.add(entry, AND)
  1225. if can_reuse is not None:
  1226. can_reuse.update(join_list)
  1227. if process_extras:
  1228. for filter in extra_filters:
  1229. self.add_filter(filter, negate=negate, can_reuse=can_reuse,
  1230. process_extras=False)
  1231. def add_q(self, q_object, used_aliases=None):
  1232. """
  1233. Adds a Q-object to the current filter.
  1234. Can also be used to add anything that has an 'add_to_query()' method.
  1235. """
  1236. if used_aliases is None:
  1237. used_aliases = self.used_aliases
  1238. if hasattr(q_object, 'add_to_query'):
  1239. # Complex custom objects are responsible for adding themselves.
  1240. q_object.add_to_query(self, used_aliases)
  1241. else:
  1242. if self.where and q_object.connector != AND and len(q_object) > 1:
  1243. self.where.start_subtree(AND)
  1244. subtree = True
  1245. else:
  1246. subtree = False
  1247. connector = AND
  1248. for child in q_object.children:
  1249. if connector == OR:
  1250. refcounts_before = self.alias_refcount.copy()
  1251. if isinstance(child, Node):
  1252. self.where.start_subtree(connector)
  1253. self.add_q(child, used_aliases)
  1254. self.where.end_subtree()
  1255. else:
  1256. self.add_filter(child, connector, q_object.negated,
  1257. can_reuse=used_aliases)
  1258. if connector == OR:
  1259. # Aliases that were newly added or not used at all need to
  1260. # be promoted to outer joins if they are nullable relations.
  1261. # (they shouldn't turn the whole conditional into the empty
  1262. # set just because they don't match anything).
  1263. self.promote_unused_aliases(refcounts_before, used_aliases)
  1264. connector = q_object.connector
  1265. if q_object.negated:
  1266. self.where.negate()
  1267. if subtree:
  1268. self.where.end_subtree()
  1269. if self.filter_is_sticky:
  1270. self.used_aliases = used_aliases
  1271. def setup_joins(self, names, opts, alias, dupe_multis, allow_many=True,
  1272. allow_explicit_fk=False, can_reuse=None, negate=False,
  1273. process_extras=True):
  1274. """
  1275. Compute the necessary table joins for the passage through the fields
  1276. given in 'names'. 'opts' is the Options class for the current model
  1277. (which gives the table we are joining to), 'alias' is the alias for the
  1278. table we are joining to. If dupe_multis is True, any many-to-many or
  1279. many-to-one joins will always create a new alias (necessary for
  1280. disjunctive filters). If can_reuse is not None, it's a list of aliases
  1281. that can be reused in these joins (nothing else can be reused in this
  1282. case). Finally, 'negate' is used in the same sense as for add_filter()
  1283. -- it indicates an exclude() filter, or something similar. It is only
  1284. passed in here so that it can be passed to a field's extra_filter() for
  1285. customised behaviour.
  1286. Returns the final field involved in the join, the target database
  1287. column (used for any 'where' constraint), the final 'opts' value and the
  1288. list of tables joined.
  1289. """
  1290. joins = [alias]
  1291. last = [0]
  1292. dupe_set = set()
  1293. exclusions = set()
  1294. extra_filters = []
  1295. for pos, name in enumerate(names):
  1296. try:
  1297. exclusions.add(int_alias)
  1298. except NameError:
  1299. pass
  1300. exclusions.add(alias)
  1301. last.append(len(joins))
  1302. if name == 'pk':
  1303. name = opts.pk.name
  1304. try:
  1305. field, model, direct, m2m = opts.get_field_by_name(name)
  1306. except FieldDoesNotExist:
  1307. for f in opts.fields:
  1308. if allow_explicit_fk and name == f.attname:
  1309. # XXX: A hack to allow foo_id to work in values() for
  1310. # backwards compatibility purposes. If we dropped that
  1311. # feature, this could be removed.
  1312. field, model, direct, m2m = opts.get_field_by_name(f.name)
  1313. break
  1314. else:
  1315. names = opts.get_all_field_names() + self.aggregate_select.keys()
  1316. raise FieldError("Cannot resolve keyword %r into field. "
  1317. "Choices are: %s" % (name, ", ".join(names)))
  1318. if not allow_many and (m2m or not direct):
  1319. for alias in joins:
  1320. self.unref_alias(alias)
  1321. raise MultiJoin(pos + 1)
  1322. if model:
  1323. # The field lives on a base class of the current model.
  1324. for int_model in opts.get_base_chain(model):
  1325. lhs_col = opts.parents[int_model].column
  1326. dedupe = lhs_col in opts.duplicate_targets
  1327. if dedupe:
  1328. exclusions.update(self.dupe_avoidance.get(
  1329. (id(opts), lhs_col), ()))
  1330. dupe_set.add((opts, lhs_col))
  1331. opts = int_model._meta
  1332. alias = self.join((alias, opts.db_table, lhs_col,
  1333. opts.pk.column), exclusions=exclusions)
  1334. joins.append(alias)
  1335. exclusions.add(alias)
  1336. for (dupe_opts, dupe_col) in dupe_set:
  1337. self.update_dupe_avoidance(dupe_opts, dupe_col, alias)
  1338. cached_data = opts._join_cache.get(name)
  1339. orig_opts = opts
  1340. dupe_col = direct and field.column or field.field.column
  1341. dedupe = dupe_col in opts.duplicate_targets
  1342. if dupe_set or dedupe:
  1343. if dedupe:
  1344. dupe_set.add((opts, dupe_col))
  1345. exclusions.update(self.dupe_avoidance.get((id(opts), dupe_col),
  1346. ()))
  1347. if process_extras and hasattr(field, 'extra_filters'):
  1348. extra_filters.extend(field.extra_filters(names, pos, negate))
  1349. if direct:
  1350. if m2m:
  1351. # Many-to-many field defined on the current model.
  1352. if cached_data:
  1353. (table1, from_col1, to_col1, table2, from_col2,
  1354. to_col2, opts, target) = cached_data
  1355. else:
  1356. table1 = field.m2m_db_table()
  1357. from_col1 = opts.pk.column
  1358. to_col1 = field.m2m_column_name()
  1359. opts = field.rel.to._meta
  1360. table2 = opts.db_table
  1361. from_col2 = field.m2m_reverse_name()
  1362. to_col2 = opts.pk.column
  1363. target = opts.pk
  1364. orig_opts._join_cache[name] = (table1, from_col1,
  1365. to_col1, table2, from_col2, to_col2, opts,
  1366. target)
  1367. int_alias = self.join((alias, table1, from_col1, to_col1),
  1368. dupe_multis, exclusions, nullable=True,
  1369. reuse=can_reuse)
  1370. if int_alias == table2 and from_col2 == to_col2:
  1371. joins.append(int_alias)
  1372. alias = int_alias
  1373. else:
  1374. alias = self.join(
  1375. (int_alias, table2, from_col2, to_col2),
  1376. dupe_multis, exclusions, nullable=True,
  1377. reuse=can_reuse)
  1378. joins.extend([int_alias, alias])
  1379. elif field.rel:
  1380. # One-to-one or many-to-one field
  1381. if cached_data:
  1382. (table, from_col, to_col, opts, target) = cached_data
  1383. else:
  1384. opts = field.rel.to._meta
  1385. target = field.rel.get_related_field()
  1386. table = opts.db_table
  1387. from_col = field.column
  1388. to_col = target.column
  1389. orig_opts._join_cache[name] = (table, from_col, to_col,
  1390. opts, target)
  1391. alias = self.join((alias, table, from_col, to_col),
  1392. exclusions=exclusions, nullable=field.null)
  1393. joins.append(alias)
  1394. else:
  1395. # Non-relation fields.
  1396. target = field
  1397. break
  1398. else:
  1399. orig_field = field
  1400. field = field.field
  1401. if m2m:
  1402. # Many-to-many field defined on the target model.
  1403. if cached_data:
  1404. (table1, from_col1, to_col1, table2, from_col2,
  1405. to_col2, opts, target) = cached_data
  1406. else:
  1407. table1 = field.m2m_db_table()
  1408. from_col1 = opts.pk.column
  1409. to_col1 = field.m2m_reverse_name()
  1410. opts = orig_field.opts
  1411. table2 = opts.db_table
  1412. from_col2 = field.m2m_column_name()
  1413. to_col2 = opts.pk.column
  1414. target = opts.pk
  1415. orig_opts._join_cache[name] = (table1, from_col1,
  1416. to_col1, table2, from_col2, to_col2, opts,
  1417. target)
  1418. int_alias = self.join((alias, table1, from_col1, to_col1),
  1419. dupe_multis, exclusions, nullable=True,
  1420. reuse=can_reuse)
  1421. alias = self.join((int_alias, table2, from_col2, to_col2),
  1422. dupe_multis, exclusions, nullable=True,
  1423. reuse=can_reuse)
  1424. joins.extend([int_alias, alias])
  1425. else:
  1426. # One-to-many field (ForeignKey defined on the target model)
  1427. if cached_data:
  1428. (table, from_col, to_col, opts, target) = cached_data
  1429. else:
  1430. local_field = opts.get_field_by_name(
  1431. field.rel.field_name)[0]
  1432. opts = orig_field.opts
  1433. table = opts.db_table
  1434. from_col = local_field.column
  1435. to_col = field.column
  1436. target = opts.pk
  1437. orig_opts._join_cache[name] = (table, from_col, to_col,
  1438. opts, target)
  1439. alias = self.join((alias, table, from_col, to_col),
  1440. dupe_multis, exclusions, nullable=True,
  1441. reuse=can_reuse)
  1442. joins.append(alias)
  1443. for (dupe_opts, dupe_col) in dupe_set:
  1444. try:
  1445. self.update_dupe_avoidance(dupe_opts, dupe_col, int_alias)
  1446. except NameError:
  1447. self.update_dupe_avoidance(dupe_opts, dupe_col, alias)
  1448. if pos != len(names) - 1:
  1449. if pos == len(names) - 2:
  1450. raise FieldError("Join on field %r not permitted. Did you misspell %r for the lookup type?" % (name, names[pos + 1]))
  1451. else:
  1452. raise FieldError("Join on field %r not permitted." % name)
  1453. return field, target, opts, joins, last, extra_filters
  1454. def trim_joins(self, target, join_list, last, trim):
  1455. """An optimization: if the final join is against the same column as
  1456. we are comparing against, we can go back one step in a join
  1457. chain and compare against the LHS of the join instead (and then
  1458. repeat the optimization). The result, potentially, involves less
  1459. table joins.
  1460. Returns a tuple
  1461. """
  1462. final = len(join_list)
  1463. penultimate = last.pop()
  1464. if penultimate == final:
  1465. penultimate = last.pop()
  1466. if trim and len(join_list) > 1:
  1467. extra = join_list[penultimate:]
  1468. join_list = join_list[:penultimate]
  1469. final = penultimate
  1470. penultimate = last.pop()
  1471. col = self.alias_map[extra[0]][LHS_JOIN_COL]
  1472. for alias in extra:
  1473. self.unref_alias(alias)
  1474. else:
  1475. col = target.column
  1476. alias = join_list[-1]
  1477. while final > 1:
  1478. join = self.alias_map[alias]
  1479. if col != join[RHS_JOIN_COL]:
  1480. break
  1481. self.unref_alias(alias)
  1482. alias = join[LHS_ALIAS]
  1483. col = join[LHS_JOIN_COL]
  1484. join_list = join_list[:-1]
  1485. final -= 1
  1486. if final == penultimate:
  1487. penultimate = last.pop()
  1488. return final, penultimate, col, alias, join_list
  1489. def update_dupe_avoidance(self, opts, col, alias):
  1490. """
  1491. For a column that is one of multiple pointing to the same table, update
  1492. the internal data structures to note that this alias shouldn't be used
  1493. for those other columns.
  1494. """
  1495. ident = id(opts)
  1496. for name in opts.duplicate_targets[col]:
  1497. try:
  1498. self.dupe_avoidance[ident, name].add(alias)
  1499. except KeyError:
  1500. self.dupe_avoidance[ident, name] = set([alias])
  1501. def split_exclude(self, filter_expr, prefix, can_reuse):
  1502. """
  1503. When doing an exclude against any kind of N-to-many relation, we need
  1504. to use a subquery. This method constructs the nested query, given the
  1505. original exclude filter (filter_expr) and the portion up to the first
  1506. N-to-many relation field.
  1507. """
  1508. query = Query(self.model, self.connection)
  1509. query.add_filter(filter_expr, can_reuse=can_reuse)
  1510. query.bump_prefix()
  1511. query.clear_ordering(True)
  1512. query.set_start(prefix)
  1513. self.add_filter(('%s__in' % prefix, query), negate=True, trim=True,
  1514. can_reuse=can_reuse)
  1515. # If there's more than one join in the inner query (before any initial
  1516. # bits were trimmed -- which means the last active table is more than
  1517. # two places into the alias list), we need to also handle the
  1518. # possibility that the earlier joins don't match anything by adding a
  1519. # comparison to NULL (e.g. in
  1520. # Tag.objects.exclude(parent__parent__name='t1'), a tag with no parent
  1521. # would otherwise be overlooked).
  1522. active_positions = [pos for (pos, count) in
  1523. enumerate(query.alias_refcount.itervalues()) if count]
  1524. if active_positions[-1] > 1:
  1525. self.add_filter(('%s__isnull' % prefix, False), negate=True,
  1526. trim=True, can_reuse=can_reuse)
  1527. def set_limits(self, low=None, high=None):
  1528. """
  1529. Adjusts the limits on the rows retrieved. We use low/high to set these,
  1530. as it makes it more Pythonic to read and write. When the SQL query is
  1531. created, they are converted to the appropriate offset and limit values.
  1532. Any limits passed in here are applied relative to the existing
  1533. constraints. So low is added to the current low value and both will be
  1534. clamped to any existing high value.
  1535. """
  1536. if high is not None:
  1537. if self.high_mark is not None:
  1538. self.high_mark = min(self.high_mark, self.low_mark + high)
  1539. else:
  1540. self.high_mark = self.low_mark + high
  1541. if low is not None:
  1542. if self.high_mark is not None:
  1543. self.low_mark = min(self.high_mark, self.low_mark + low)
  1544. else:
  1545. self.low_mark = self.low_mark + low
  1546. def clear_limits(self):
  1547. """
  1548. Clears any existing limits.
  1549. """
  1550. self.low_mark, self.high_mark = 0, None
  1551. def can_filter(self):
  1552. """
  1553. Returns True if adding filters to this instance is still possible.
  1554. Typically, this means no limits or offsets have been put on the results.
  1555. """
  1556. return not (self.low_mark or self.high_mark)
  1557. def clear_select_fields(self):
  1558. """
  1559. Clears the list of fields to select (but not extra_select columns).
  1560. Some queryset types completely replace any existing list of select
  1561. columns.
  1562. """
  1563. self.select = []
  1564. self.select_fields = []
  1565. def add_fields(self, field_names, allow_m2m=True):
  1566. """
  1567. Adds the given (model) fields to the select set. The field names are
  1568. added in the order specified.
  1569. """
  1570. alias = self.get_initial_alias()
  1571. opts = self.get_meta()
  1572. try:
  1573. for name in field_names:
  1574. field, target, u2, joins, u3, u4 = self.setup_joins(
  1575. name.split(LOOKUP_SEP), opts, alias, False, allow_m2m,
  1576. True)
  1577. final_alias = joins[-1]
  1578. col = target.column
  1579. if len(joins) > 1:
  1580. join = self.alias_map[final_alias]
  1581. if col == join[RHS_JOIN_COL]:
  1582. self.unref_alias(final_alias)
  1583. final_alias = join[LHS_ALIAS]
  1584. col = join[LHS_JOIN_COL]
  1585. joins = joins[:-1]
  1586. self.promote_alias_chain(joins[1:])
  1587. self.select.append((final_alias, col))
  1588. self.select_fields.append(field)
  1589. except MultiJoin:
  1590. raise FieldError("Invalid field name: '%s'" % name)
  1591. except FieldError:
  1592. names = opts.get_all_field_names() + self.extra_select.keys() + self.aggregate_select.keys()
  1593. names.sort()
  1594. raise FieldError("Cannot resolve keyword %r into field. "
  1595. "Choices are: %s" % (name, ", ".join(names)))
  1596. def add_ordering(self, *ordering):
  1597. """
  1598. Adds items from the 'ordering' sequence to the query's "order by"
  1599. clause. These items are either field names (not column names) --
  1600. possibly with a direction prefix ('-' or '?') -- or ordinals,
  1601. corresponding to column positions in the 'select' list.
  1602. If 'ordering' is empty, all ordering is cleared from the query.
  1603. """
  1604. errors = []
  1605. for item in ordering:
  1606. if not ORDER_PATTERN.match(item):
  1607. errors.append(item)
  1608. if errors:
  1609. raise FieldError('Invalid order_by arguments: %s' % errors)
  1610. if ordering:
  1611. self.order_by.extend(ordering)
  1612. else:
  1613. self.default_ordering = False
  1614. def clear_ordering(self, force_empty=False):
  1615. """
  1616. Removes any ordering settings. If 'force_empty' is True, there will be
  1617. no ordering in the resulting query (not even the model's default).
  1618. """
  1619. self.order_by = []
  1620. self.extra_order_by = ()
  1621. if force_empty:
  1622. self.default_ordering = False
  1623. def set_group_by(self):
  1624. """
  1625. Expands the GROUP BY clause required by the query.
  1626. This will usually be the set of all non-aggregate fields in the
  1627. return data. If the database backend supports grouping by the
  1628. primary key, and the query would be equivalent, the optimization
  1629. will be made automatically.
  1630. """
  1631. if self.connection.features.allows_group_by_pk:
  1632. if len(self.select) == len(self.model._meta.fields):
  1633. self.group_by.append('.'.join([self.model._meta.db_table,
  1634. self.model._meta.pk.column]))
  1635. return
  1636. for sel in self.select:
  1637. self.group_by.append(sel)
  1638. def add_count_column(self):
  1639. """
  1640. Converts the query to do count(...) or count(distinct(pk)) in order to
  1641. get its size.
  1642. """
  1643. if not self.distinct:
  1644. if not self.select:
  1645. count = self.aggregates_module.Count('*', is_summary=True)
  1646. else:
  1647. assert len(self.select) == 1, \
  1648. "Cannot add count col with multiple cols in 'select': %r" % self.select
  1649. count = self.aggregates_module.Count(self.select[0])
  1650. else:
  1651. opts = self.model._meta
  1652. if not self.select:
  1653. count = self.aggregates_module.Count((self.join((None, opts.db_table, None, None)), opts.pk.column),
  1654. is_summary=True, distinct=True)
  1655. else:
  1656. # Because of SQL portability issues, multi-column, distinct
  1657. # counts need a sub-query -- see get_count() for details.
  1658. assert len(self.select) == 1, \
  1659. "Cannot add count col with multiple cols in 'select'."
  1660. count = self.aggregates_module.Count(self.select[0], distinct=True)
  1661. # Distinct handling is done in Count(), so don't do it at this
  1662. # level.
  1663. self.distinct = False
  1664. self.aggregate_select = {None: count}
  1665. def add_select_related(self, fields):
  1666. """
  1667. Sets up the select_related data structure so that we only select
  1668. certain related models (as opposed to all models, when
  1669. self.select_related=True).
  1670. """
  1671. field_dict = {}
  1672. for field in fields:
  1673. d = field_dict
  1674. for part in field.split(LOOKUP_SEP):
  1675. d = d.setdefault(part, {})
  1676. self.select_related = field_dict
  1677. self.related_select_cols = []
  1678. self.related_select_fields = []
  1679. def add_extra(self, select, select_params, where, params, tables, order_by):
  1680. """
  1681. Adds data to the various extra_* attributes for user-created additions
  1682. to the query.
  1683. """
  1684. if select:
  1685. # We need to pair any placeholder markers in the 'select'
  1686. # dictionary with their parameters in 'select_params' so that
  1687. # subsequent updates to the select dictionary also adjust the
  1688. # parameters appropriately.
  1689. select_pairs = SortedDict()
  1690. if select_params:
  1691. param_iter = iter(select_params)
  1692. else:
  1693. param_iter = iter([])
  1694. for name, entry in select.items():
  1695. entry = force_unicode(entry)
  1696. entry_params = []
  1697. pos = entry.find("%s")
  1698. while pos != -1:
  1699. entry_params.append(param_iter.next())
  1700. pos = entry.find("%s", pos + 2)
  1701. select_pairs[name] = (entry, entry_params)
  1702. # This is order preserving, since self.extra_select is a SortedDict.
  1703. self.extra_select.update(select_pairs)
  1704. if where:
  1705. self.extra_where += tuple(where)
  1706. if params:
  1707. self.extra_params += tuple(params)
  1708. if tables:
  1709. self.extra_tables += tuple(tables)
  1710. if order_by:
  1711. self.extra_order_by = order_by
  1712. def trim_extra_select(self, names):
  1713. """
  1714. Removes any aliases in the extra_select dictionary that aren't in
  1715. 'names'.
  1716. This is needed if we are selecting certain values that don't incldue
  1717. all of the extra_select names.
  1718. """
  1719. for key in set(self.extra_select).difference(set(names)):
  1720. del self.extra_select[key]
  1721. def set_start(self, start):
  1722. """
  1723. Sets the table from which to start joining. The start position is
  1724. specified by the related attribute from the base model. This will
  1725. automatically set to the select column to be the column linked from the
  1726. previous table.
  1727. This method is primarily for internal use and the error checking isn't
  1728. as friendly as add_filter(). Mostly useful for querying directly
  1729. against the join table of many-to-many relation in a subquery.
  1730. """
  1731. opts = self.model._meta
  1732. alias = self.get_initial_alias()
  1733. field, col, opts, joins, last, extra = self.setup_joins(
  1734. start.split(LOOKUP_SEP), opts, alias, False)
  1735. select_col = self.alias_map[joins[1]][LHS_JOIN_COL]
  1736. select_alias = alias
  1737. # The call to setup_joins added an extra reference to everything in
  1738. # joins. Reverse that.
  1739. for alias in joins:
  1740. self.unref_alias(alias)
  1741. # We might be able to trim some joins from the front of this query,
  1742. # providing that we only traverse "always equal" connections (i.e. rhs
  1743. # is *always* the same value as lhs).
  1744. for alias in joins[1:]:
  1745. join_info = self.alias_map[alias]
  1746. if (join_info[LHS_JOIN_COL] != select_col
  1747. or join_info[JOIN_TYPE] != self.INNER):
  1748. break
  1749. self.unref_alias(select_alias)
  1750. select_alias = join_info[RHS_ALIAS]
  1751. select_col = join_info[RHS_JOIN_COL]
  1752. self.select = [(select_alias, select_col)]
  1753. def execute_sql(self, result_type=MULTI):
  1754. """
  1755. Run the query against the database and returns the result(s). The
  1756. return value is a single data item if result_type is SINGLE, or an
  1757. iterator over the results if the result_type is MULTI.
  1758. result_type is either MULTI (use fetchmany() to retrieve all rows),
  1759. SINGLE (only retrieve a single row), or None (no results expected, but
  1760. the cursor is returned, since it's used by subclasses such as
  1761. InsertQuery).
  1762. """
  1763. try:
  1764. sql, params = self.as_sql()
  1765. if not sql:
  1766. raise EmptyResultSet
  1767. except EmptyResultSet:
  1768. if result_type == MULTI:
  1769. return empty_iter()
  1770. else:
  1771. return
  1772. cursor = self.connection.cursor()
  1773. cursor.execute(sql, params)
  1774. if not result_type:
  1775. return cursor
  1776. if result_type == SINGLE:
  1777. if self.ordering_aliases:
  1778. return cursor.fetchone()[:-len(results.ordering_aliases)]
  1779. return cursor.fetchone()
  1780. # The MULTI case.
  1781. if self.ordering_aliases:
  1782. result = order_modified_iter(cursor, len(self.ordering_aliases),
  1783. self.connection.features.empty_fetchmany_value)
  1784. else:
  1785. result = iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
  1786. self.connection.features.empty_fetchmany_value)
  1787. if not self.connection.features.can_use_chunked_reads:
  1788. # If we are using non-chunked reads, we return the same data
  1789. # structure as normally, but ensure it is all read into memory
  1790. # before going any further.
  1791. return list(result)
  1792. return result
  1793. # Use the backend's custom Query class if it defines one. Otherwise, use the
  1794. # default.
  1795. if connection.features.uses_custom_query_class:
  1796. Query = connection.ops.query_class(BaseQuery)
  1797. else:
  1798. Query = BaseQuery
  1799. def get_order_dir(field, default='ASC'):
  1800. """
  1801. Returns the field name and direction for an order specification. For
  1802. example, '-foo' is returned as ('foo', 'DESC').
  1803. The 'default' param is used to indicate which way no prefix (or a '+'
  1804. prefix) should sort. The '-' prefix always sorts the opposite way.
  1805. """
  1806. dirn = ORDER_DIR[default]
  1807. if field[0] == '-':
  1808. return field[1:], dirn[1]
  1809. return field, dirn[0]
  1810. def empty_iter():
  1811. """
  1812. Returns an iterator containing no results.
  1813. """
  1814. yield iter([]).next()
  1815. def order_modified_iter(cursor, trim, sentinel):
  1816. """
  1817. Yields blocks of rows from a cursor. We use this iterator in the special
  1818. case when extra output columns have been added to support ordering
  1819. requirements. We must trim those extra columns before anything else can use
  1820. the results, since they're only needed to make the SQL valid.
  1821. """
  1822. for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
  1823. sentinel):
  1824. yield [r[:-trim] for r in rows]
  1825. def setup_join_cache(sender, **kwargs):
  1826. """
  1827. The information needed to join between model fields is something that is
  1828. invariant over the life of the model, so we cache it in the model's Options
  1829. class, rather than recomputing it all the time.
  1830. This method initialises the (empty) cache when the model is created.
  1831. """
  1832. sender._meta._join_cache = {}
  1833. signals.class_prepared.connect(setup_join_cache)