query.py 82 KB

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