You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compiler.py 53 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. import re
  2. import warnings
  3. from itertools import chain
  4. from django.core.exceptions import FieldError
  5. from django.db.models.constants import LOOKUP_SEP
  6. from django.db.models.expressions import OrderBy, Random, RawSQL, Ref
  7. from django.db.models.query_utils import QueryWrapper, select_related_descend
  8. from django.db.models.sql.constants import (
  9. CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE,
  10. )
  11. from django.db.models.sql.datastructures import EmptyResultSet
  12. from django.db.models.sql.query import Query, get_order_dir
  13. from django.db.transaction import TransactionManagementError
  14. from django.db.utils import DatabaseError
  15. from django.utils.deprecation import RemovedInDjango110Warning
  16. from django.utils.six.moves import zip
  17. class SQLCompiler(object):
  18. def __init__(self, query, connection, using):
  19. self.query = query
  20. self.connection = connection
  21. self.using = using
  22. self.quote_cache = {'*': '*'}
  23. # The select, klass_info, and annotations are needed by QuerySet.iterator()
  24. # these are set as a side-effect of executing the query. Note that we calculate
  25. # separately a list of extra select columns needed for grammatical correctness
  26. # of the query, but these columns are not included in self.select.
  27. self.select = None
  28. self.annotation_col_map = None
  29. self.klass_info = None
  30. self.ordering_parts = re.compile(r'(.*)\s(ASC|DESC)(.*)')
  31. self.subquery = False
  32. def setup_query(self):
  33. if all(self.query.alias_refcount[a] == 0 for a in self.query.tables):
  34. self.query.get_initial_alias()
  35. self.select, self.klass_info, self.annotation_col_map = self.get_select()
  36. self.col_count = len(self.select)
  37. def pre_sql_setup(self):
  38. """
  39. Does any necessary class setup immediately prior to producing SQL. This
  40. is for things that can't necessarily be done in __init__ because we
  41. might not have all the pieces in place at that time.
  42. """
  43. self.setup_query()
  44. order_by = self.get_order_by()
  45. self.where, self.having = self.query.where.split_having()
  46. extra_select = self.get_extra_select(order_by, self.select)
  47. group_by = self.get_group_by(self.select + extra_select, order_by)
  48. return extra_select, order_by, group_by
  49. def get_group_by(self, select, order_by):
  50. """
  51. Returns a list of 2-tuples of form (sql, params).
  52. The logic of what exactly the GROUP BY clause contains is hard
  53. to describe in other words than "if it passes the test suite,
  54. then it is correct".
  55. """
  56. # Some examples:
  57. # SomeModel.objects.annotate(Count('somecol'))
  58. # GROUP BY: all fields of the model
  59. #
  60. # SomeModel.objects.values('name').annotate(Count('somecol'))
  61. # GROUP BY: name
  62. #
  63. # SomeModel.objects.annotate(Count('somecol')).values('name')
  64. # GROUP BY: all cols of the model
  65. #
  66. # SomeModel.objects.values('name', 'pk').annotate(Count('somecol')).values('pk')
  67. # GROUP BY: name, pk
  68. #
  69. # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk')
  70. # GROUP BY: name, pk
  71. #
  72. # In fact, the self.query.group_by is the minimal set to GROUP BY. It
  73. # can't be ever restricted to a smaller set, but additional columns in
  74. # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately
  75. # the end result is that it is impossible to force the query to have
  76. # a chosen GROUP BY clause - you can almost do this by using the form:
  77. # .values(*wanted_cols).annotate(AnAggregate())
  78. # but any later annotations, extra selects, values calls that
  79. # refer some column outside of the wanted_cols, order_by, or even
  80. # filter calls can alter the GROUP BY clause.
  81. # The query.group_by is either None (no GROUP BY at all), True
  82. # (group by select fields), or a list of expressions to be added
  83. # to the group by.
  84. if self.query.group_by is None:
  85. return []
  86. expressions = []
  87. if self.query.group_by is not True:
  88. # If the group by is set to a list (by .values() call most likely),
  89. # then we need to add everything in it to the GROUP BY clause.
  90. # Backwards compatibility hack for setting query.group_by. Remove
  91. # when we have public API way of forcing the GROUP BY clause.
  92. # Converts string references to expressions.
  93. for expr in self.query.group_by:
  94. if not hasattr(expr, 'as_sql'):
  95. expressions.append(self.query.resolve_ref(expr))
  96. else:
  97. expressions.append(expr)
  98. # Note that even if the group_by is set, it is only the minimal
  99. # set to group by. So, we need to add cols in select, order_by, and
  100. # having into the select in any case.
  101. for expr, _, _ in select:
  102. cols = expr.get_group_by_cols()
  103. for col in cols:
  104. expressions.append(col)
  105. for expr, (sql, params, is_ref) in order_by:
  106. if expr.contains_aggregate:
  107. continue
  108. # We can skip References to select clause, as all expressions in
  109. # the select clause are already part of the group by.
  110. if is_ref:
  111. continue
  112. expressions.extend(expr.get_source_expressions())
  113. having_group_by = self.having.get_group_by_cols() if self.having else ()
  114. for expr in having_group_by:
  115. expressions.append(expr)
  116. result = []
  117. seen = set()
  118. expressions = self.collapse_group_by(expressions, having_group_by)
  119. for expr in expressions:
  120. sql, params = self.compile(expr)
  121. if (sql, tuple(params)) not in seen:
  122. result.append((sql, params))
  123. seen.add((sql, tuple(params)))
  124. return result
  125. def collapse_group_by(self, expressions, having):
  126. # If the DB can group by primary key, then group by the primary key of
  127. # query's main model. Note that for PostgreSQL the GROUP BY clause must
  128. # include the primary key of every table, but for MySQL it is enough to
  129. # have the main table's primary key.
  130. if self.connection.features.allows_group_by_pk:
  131. # The logic here is: if the main model's primary key is in the
  132. # query, then set new_expressions to that field. If that happens,
  133. # then also add having expressions to group by.
  134. pk = None
  135. for expr in expressions:
  136. # Is this a reference to query's base table primary key? If the
  137. # expression isn't a Col-like, then skip the expression.
  138. if (getattr(expr, 'target', None) == self.query.model._meta.pk and
  139. getattr(expr, 'alias', None) == self.query.tables[0]):
  140. pk = expr
  141. break
  142. if pk:
  143. # MySQLism: Columns in HAVING clause must be added to the GROUP BY.
  144. expressions = [pk] + [expr for expr in expressions if expr in having]
  145. elif self.connection.features.allows_group_by_selected_pks:
  146. # Filter out all expressions associated with a table's primary key
  147. # present in the grouped columns. This is done by identifying all
  148. # tables that have their primary key included in the grouped
  149. # columns and removing non-primary key columns referring to them.
  150. pks = {expr for expr in expressions if hasattr(expr, 'target') and expr.target.primary_key}
  151. aliases = {expr.alias for expr in pks}
  152. expressions = [
  153. expr for expr in expressions if expr in pks or getattr(expr, 'alias', None) not in aliases
  154. ]
  155. return expressions
  156. def get_select(self):
  157. """
  158. Returns three values:
  159. - a list of 3-tuples of (expression, (sql, params), alias)
  160. - a klass_info structure,
  161. - a dictionary of annotations
  162. The (sql, params) is what the expression will produce, and alias is the
  163. "AS alias" for the column (possibly None).
  164. The klass_info structure contains the following information:
  165. - Which model to instantiate
  166. - Which columns for that model are present in the query (by
  167. position of the select clause).
  168. - related_klass_infos: [f, klass_info] to descent into
  169. The annotations is a dictionary of {'attname': column position} values.
  170. """
  171. select = []
  172. klass_info = None
  173. annotations = {}
  174. select_idx = 0
  175. for alias, (sql, params) in self.query.extra_select.items():
  176. annotations[alias] = select_idx
  177. select.append((RawSQL(sql, params), alias))
  178. select_idx += 1
  179. assert not (self.query.select and self.query.default_cols)
  180. if self.query.default_cols:
  181. select_list = []
  182. for c in self.get_default_columns():
  183. select_list.append(select_idx)
  184. select.append((c, None))
  185. select_idx += 1
  186. klass_info = {
  187. 'model': self.query.model,
  188. 'select_fields': select_list,
  189. }
  190. # self.query.select is a special case. These columns never go to
  191. # any model.
  192. for col in self.query.select:
  193. select.append((col, None))
  194. select_idx += 1
  195. for alias, annotation in self.query.annotation_select.items():
  196. annotations[alias] = select_idx
  197. select.append((annotation, alias))
  198. select_idx += 1
  199. if self.query.select_related:
  200. related_klass_infos = self.get_related_selections(select)
  201. klass_info['related_klass_infos'] = related_klass_infos
  202. def get_select_from_parent(klass_info):
  203. for ki in klass_info['related_klass_infos']:
  204. if ki['from_parent']:
  205. ki['select_fields'] = (klass_info['select_fields'] +
  206. ki['select_fields'])
  207. get_select_from_parent(ki)
  208. get_select_from_parent(klass_info)
  209. ret = []
  210. for col, alias in select:
  211. ret.append((col, self.compile(col, select_format=True), alias))
  212. return ret, klass_info, annotations
  213. def get_order_by(self):
  214. """
  215. Returns a list of 2-tuples of form (expr, (sql, params, is_ref)) for the
  216. ORDER BY clause.
  217. The order_by clause can alter the select clause (for example it
  218. can add aliases to clauses that do not yet have one, or it can
  219. add totally new select clauses).
  220. """
  221. if self.query.extra_order_by:
  222. ordering = self.query.extra_order_by
  223. elif not self.query.default_ordering:
  224. ordering = self.query.order_by
  225. else:
  226. ordering = (self.query.order_by or self.query.get_meta().ordering or [])
  227. if self.query.standard_ordering:
  228. asc, desc = ORDER_DIR['ASC']
  229. else:
  230. asc, desc = ORDER_DIR['DESC']
  231. order_by = []
  232. for pos, field in enumerate(ordering):
  233. if hasattr(field, 'resolve_expression'):
  234. if not isinstance(field, OrderBy):
  235. field = field.asc()
  236. if not self.query.standard_ordering:
  237. field.reverse_ordering()
  238. order_by.append((field, False))
  239. continue
  240. if field == '?': # random
  241. order_by.append((OrderBy(Random()), False))
  242. continue
  243. col, order = get_order_dir(field, asc)
  244. descending = True if order == 'DESC' else False
  245. if col in self.query.annotation_select:
  246. # Reference to expression in SELECT clause
  247. order_by.append((
  248. OrderBy(Ref(col, self.query.annotation_select[col]), descending=descending),
  249. True))
  250. continue
  251. if col in self.query.annotations:
  252. # References to an expression which is masked out of the SELECT clause
  253. order_by.append((
  254. OrderBy(self.query.annotations[col], descending=descending),
  255. False))
  256. continue
  257. if '.' in field:
  258. # This came in through an extra(order_by=...) addition. Pass it
  259. # on verbatim.
  260. table, col = col.split('.', 1)
  261. order_by.append((
  262. OrderBy(
  263. RawSQL('%s.%s' % (self.quote_name_unless_alias(table), col), []),
  264. descending=descending
  265. ), False))
  266. continue
  267. if not self.query._extra or col not in self.query._extra:
  268. # 'col' is of the form 'field' or 'field1__field2' or
  269. # '-field1__field2__field', etc.
  270. order_by.extend(self.find_ordering_name(
  271. field, self.query.get_meta(), default_order=asc))
  272. else:
  273. if col not in self.query.extra_select:
  274. order_by.append((
  275. OrderBy(RawSQL(*self.query.extra[col]), descending=descending),
  276. False))
  277. else:
  278. order_by.append((
  279. OrderBy(Ref(col, RawSQL(*self.query.extra[col])), descending=descending),
  280. True))
  281. result = []
  282. seen = set()
  283. for expr, is_ref in order_by:
  284. resolved = expr.resolve_expression(
  285. self.query, allow_joins=True, reuse=None)
  286. sql, params = self.compile(resolved)
  287. # Don't add the same column twice, but the order direction is
  288. # not taken into account so we strip it. When this entire method
  289. # is refactored into expressions, then we can check each part as we
  290. # generate it.
  291. without_ordering = self.ordering_parts.search(sql).group(1)
  292. if (without_ordering, tuple(params)) in seen:
  293. continue
  294. seen.add((without_ordering, tuple(params)))
  295. result.append((resolved, (sql, params, is_ref)))
  296. return result
  297. def get_extra_select(self, order_by, select):
  298. extra_select = []
  299. select_sql = [t[1] for t in select]
  300. if self.query.distinct and not self.query.distinct_fields:
  301. for expr, (sql, params, is_ref) in order_by:
  302. without_ordering = self.ordering_parts.search(sql).group(1)
  303. if not is_ref and (without_ordering, params) not in select_sql:
  304. extra_select.append((expr, (without_ordering, params), None))
  305. return extra_select
  306. def __call__(self, name):
  307. """
  308. Backwards-compatibility shim so that calling a SQLCompiler is equivalent to
  309. calling its quote_name_unless_alias method.
  310. """
  311. warnings.warn(
  312. "Calling a SQLCompiler directly is deprecated. "
  313. "Call compiler.quote_name_unless_alias instead.",
  314. RemovedInDjango110Warning, stacklevel=2)
  315. return self.quote_name_unless_alias(name)
  316. def quote_name_unless_alias(self, name):
  317. """
  318. A wrapper around connection.ops.quote_name that doesn't quote aliases
  319. for table names. This avoids problems with some SQL dialects that treat
  320. quoted strings specially (e.g. PostgreSQL).
  321. """
  322. if name in self.quote_cache:
  323. return self.quote_cache[name]
  324. if ((name in self.query.alias_map and name not in self.query.table_map) or
  325. name in self.query.extra_select or (
  326. name in self.query.external_aliases and name not in self.query.table_map)):
  327. self.quote_cache[name] = name
  328. return name
  329. r = self.connection.ops.quote_name(name)
  330. self.quote_cache[name] = r
  331. return r
  332. def compile(self, node, select_format=False):
  333. vendor_impl = getattr(node, 'as_' + self.connection.vendor, None)
  334. if vendor_impl:
  335. sql, params = vendor_impl(self, self.connection)
  336. else:
  337. sql, params = node.as_sql(self, self.connection)
  338. if select_format and not self.subquery:
  339. return node.output_field.select_format(self, sql, params)
  340. return sql, params
  341. def as_sql(self, with_limits=True, with_col_aliases=False, subquery=False):
  342. """
  343. Creates the SQL for this query. Returns the SQL string and list of
  344. parameters.
  345. If 'with_limits' is False, any limit/offset information is not included
  346. in the query.
  347. """
  348. self.subquery = subquery
  349. refcounts_before = self.query.alias_refcount.copy()
  350. try:
  351. extra_select, order_by, group_by = self.pre_sql_setup()
  352. distinct_fields = self.get_distinct()
  353. # This must come after 'select', 'ordering', and 'distinct' -- see
  354. # docstring of get_from_clause() for details.
  355. from_, f_params = self.get_from_clause()
  356. where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  357. having, h_params = self.compile(self.having) if self.having is not None else ("", [])
  358. params = []
  359. result = ['SELECT']
  360. if self.query.distinct:
  361. result.append(self.connection.ops.distinct_sql(distinct_fields))
  362. out_cols = []
  363. col_idx = 1
  364. for _, (s_sql, s_params), alias in self.select + extra_select:
  365. if alias:
  366. s_sql = '%s AS %s' % (s_sql, self.connection.ops.quote_name(alias))
  367. elif with_col_aliases:
  368. s_sql = '%s AS %s' % (s_sql, 'Col%d' % col_idx)
  369. col_idx += 1
  370. params.extend(s_params)
  371. out_cols.append(s_sql)
  372. result.append(', '.join(out_cols))
  373. result.append('FROM')
  374. result.extend(from_)
  375. params.extend(f_params)
  376. if where:
  377. result.append('WHERE %s' % where)
  378. params.extend(w_params)
  379. grouping = []
  380. for g_sql, g_params in group_by:
  381. grouping.append(g_sql)
  382. params.extend(g_params)
  383. if grouping:
  384. if distinct_fields:
  385. raise NotImplementedError(
  386. "annotate() + distinct(fields) is not implemented.")
  387. if not order_by:
  388. order_by = self.connection.ops.force_no_ordering()
  389. result.append('GROUP BY %s' % ', '.join(grouping))
  390. if having:
  391. result.append('HAVING %s' % having)
  392. params.extend(h_params)
  393. if order_by:
  394. ordering = []
  395. for _, (o_sql, o_params, _) in order_by:
  396. ordering.append(o_sql)
  397. params.extend(o_params)
  398. result.append('ORDER BY %s' % ', '.join(ordering))
  399. if with_limits:
  400. if self.query.high_mark is not None:
  401. result.append('LIMIT %d' % (self.query.high_mark - self.query.low_mark))
  402. if self.query.low_mark:
  403. if self.query.high_mark is None:
  404. val = self.connection.ops.no_limit_value()
  405. if val:
  406. result.append('LIMIT %d' % val)
  407. result.append('OFFSET %d' % self.query.low_mark)
  408. if self.query.select_for_update and self.connection.features.has_select_for_update:
  409. if self.connection.get_autocommit():
  410. raise TransactionManagementError(
  411. "select_for_update cannot be used outside of a transaction."
  412. )
  413. # If we've been asked for a NOWAIT query but the backend does
  414. # not support it, raise a DatabaseError otherwise we could get
  415. # an unexpected deadlock.
  416. nowait = self.query.select_for_update_nowait
  417. if nowait and not self.connection.features.has_select_for_update_nowait:
  418. raise DatabaseError('NOWAIT is not supported on this database backend.')
  419. result.append(self.connection.ops.for_update_sql(nowait=nowait))
  420. return ' '.join(result), tuple(params)
  421. finally:
  422. # Finally do cleanup - get rid of the joins we created above.
  423. self.query.reset_refcounts(refcounts_before)
  424. def as_nested_sql(self):
  425. """
  426. Perform the same functionality as the as_sql() method, returning an
  427. SQL string and parameters. However, the alias prefixes are bumped
  428. beforehand (in a copy -- the current query isn't changed), and any
  429. ordering is removed if the query is unsliced.
  430. Used when nesting this query inside another.
  431. """
  432. obj = self.query.clone()
  433. if obj.low_mark == 0 and obj.high_mark is None and not self.query.distinct_fields:
  434. # If there is no slicing in use, then we can safely drop all ordering
  435. obj.clear_ordering(True)
  436. nested_sql = obj.get_compiler(connection=self.connection).as_sql(subquery=True)
  437. if nested_sql == ('', ()):
  438. raise EmptyResultSet
  439. return nested_sql
  440. def get_default_columns(self, start_alias=None, opts=None, from_parent=None):
  441. """
  442. Computes the default columns for selecting every field in the base
  443. model. Will sometimes be called to pull in related models (e.g. via
  444. select_related), in which case "opts" and "start_alias" will be given
  445. to provide a starting point for the traversal.
  446. Returns a list of strings, quoted appropriately for use in SQL
  447. directly, as well as a set of aliases used in the select statement (if
  448. 'as_pairs' is True, returns a list of (alias, col_name) pairs instead
  449. of strings as the first component and None as the second component).
  450. """
  451. result = []
  452. if opts is None:
  453. opts = self.query.get_meta()
  454. only_load = self.deferred_to_columns()
  455. if not start_alias:
  456. start_alias = self.query.get_initial_alias()
  457. # The 'seen_models' is used to optimize checking the needed parent
  458. # alias for a given field. This also includes None -> start_alias to
  459. # be used by local fields.
  460. seen_models = {None: start_alias}
  461. for field in opts.concrete_fields:
  462. model = field.model._meta.concrete_model
  463. # A proxy model will have a different model and concrete_model. We
  464. # will assign None if the field belongs to this model.
  465. if model == opts.model:
  466. model = None
  467. if from_parent and model is not None and issubclass(
  468. from_parent._meta.concrete_model, model._meta.concrete_model):
  469. # Avoid loading data for already loaded parents.
  470. # We end up here in the case select_related() resolution
  471. # proceeds from parent model to child model. In that case the
  472. # parent model data is already present in the SELECT clause,
  473. # and we want to avoid reloading the same data again.
  474. continue
  475. if field.model in only_load and field.attname not in only_load[field.model]:
  476. continue
  477. alias = self.query.join_parent_model(opts, model, start_alias,
  478. seen_models)
  479. column = field.get_col(alias)
  480. result.append(column)
  481. return result
  482. def get_distinct(self):
  483. """
  484. Returns a quoted list of fields to use in DISTINCT ON part of the query.
  485. Note that this method can alter the tables in the query, and thus it
  486. must be called before get_from_clause().
  487. """
  488. qn = self.quote_name_unless_alias
  489. qn2 = self.connection.ops.quote_name
  490. result = []
  491. opts = self.query.get_meta()
  492. for name in self.query.distinct_fields:
  493. parts = name.split(LOOKUP_SEP)
  494. _, targets, alias, joins, path, _ = self._setup_joins(parts, opts, None)
  495. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  496. for target in targets:
  497. if name in self.query.annotation_select:
  498. result.append(name)
  499. else:
  500. result.append("%s.%s" % (qn(alias), qn2(target.column)))
  501. return result
  502. def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
  503. already_seen=None):
  504. """
  505. Returns the table alias (the name might be ambiguous, the alias will
  506. not be) and column name for ordering by the given 'name' parameter.
  507. The 'name' is of the form 'field1__field2__...__fieldN'.
  508. """
  509. name, order = get_order_dir(name, default_order)
  510. descending = True if order == 'DESC' else False
  511. pieces = name.split(LOOKUP_SEP)
  512. field, targets, alias, joins, path, opts = self._setup_joins(pieces, opts, alias)
  513. # If we get to this point and the field is a relation to another model,
  514. # append the default ordering for that model unless the attribute name
  515. # of the field is specified.
  516. if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name:
  517. # Firstly, avoid infinite loops.
  518. if not already_seen:
  519. already_seen = set()
  520. join_tuple = tuple(getattr(self.query.alias_map[j], 'join_cols', None) for j in joins)
  521. if join_tuple in already_seen:
  522. raise FieldError('Infinite loop caused by ordering.')
  523. already_seen.add(join_tuple)
  524. results = []
  525. for item in opts.ordering:
  526. results.extend(self.find_ordering_name(item, opts, alias,
  527. order, already_seen))
  528. return results
  529. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  530. return [(OrderBy(t.get_col(alias), descending=descending), False) for t in targets]
  531. def _setup_joins(self, pieces, opts, alias):
  532. """
  533. A helper method for get_order_by and get_distinct.
  534. Note that get_ordering and get_distinct must produce same target
  535. columns on same input, as the prefixes of get_ordering and get_distinct
  536. must match. Executing SQL where this is not true is an error.
  537. """
  538. if not alias:
  539. alias = self.query.get_initial_alias()
  540. field, targets, opts, joins, path = self.query.setup_joins(
  541. pieces, opts, alias)
  542. alias = joins[-1]
  543. return field, targets, alias, joins, path, opts
  544. def get_from_clause(self):
  545. """
  546. Returns a list of strings that are joined together to go after the
  547. "FROM" part of the query, as well as a list any extra parameters that
  548. need to be included. Sub-classes, can override this to create a
  549. from-clause via a "select".
  550. This should only be called after any SQL construction methods that
  551. might change the tables we need. This means the select columns,
  552. ordering and distinct must be done first.
  553. """
  554. result = []
  555. params = []
  556. for alias in self.query.tables:
  557. if not self.query.alias_refcount[alias]:
  558. continue
  559. try:
  560. from_clause = self.query.alias_map[alias]
  561. except KeyError:
  562. # Extra tables can end up in self.tables, but not in the
  563. # alias_map if they aren't in a join. That's OK. We skip them.
  564. continue
  565. clause_sql, clause_params = self.compile(from_clause)
  566. result.append(clause_sql)
  567. params.extend(clause_params)
  568. for t in self.query.extra_tables:
  569. alias, _ = self.query.table_alias(t)
  570. # Only add the alias if it's not already present (the table_alias()
  571. # call increments the refcount, so an alias refcount of one means
  572. # this is the only reference).
  573. if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1:
  574. result.append(', %s' % self.quote_name_unless_alias(alias))
  575. return result, params
  576. def get_related_selections(self, select, opts=None, root_alias=None, cur_depth=1,
  577. requested=None, restricted=None):
  578. """
  579. Fill in the information needed for a select_related query. The current
  580. depth is measured as the number of connections away from the root model
  581. (for example, cur_depth=1 means we are looking at models with direct
  582. connections to the root model).
  583. """
  584. def _get_field_choices():
  585. direct_choices = (f.name for f in opts.fields if f.is_relation)
  586. reverse_choices = (
  587. f.field.related_query_name()
  588. for f in opts.related_objects if f.field.unique
  589. )
  590. return chain(direct_choices, reverse_choices)
  591. related_klass_infos = []
  592. if not restricted and self.query.max_depth and cur_depth > self.query.max_depth:
  593. # We've recursed far enough; bail out.
  594. return related_klass_infos
  595. if not opts:
  596. opts = self.query.get_meta()
  597. root_alias = self.query.get_initial_alias()
  598. only_load = self.query.get_loaded_field_names()
  599. # Setup for the case when only particular related fields should be
  600. # included in the related selection.
  601. fields_found = set()
  602. if requested is None:
  603. if isinstance(self.query.select_related, dict):
  604. requested = self.query.select_related
  605. restricted = True
  606. else:
  607. restricted = False
  608. def get_related_klass_infos(klass_info, related_klass_infos):
  609. klass_info['related_klass_infos'] = related_klass_infos
  610. for f in opts.fields:
  611. field_model = f.model._meta.concrete_model
  612. fields_found.add(f.name)
  613. if restricted:
  614. next = requested.get(f.name, {})
  615. if not f.is_relation:
  616. # If a non-related field is used like a relation,
  617. # or if a single non-relational field is given.
  618. if next or (cur_depth == 1 and f.name in requested):
  619. raise FieldError(
  620. "Non-relational field given in select_related: '%s'. "
  621. "Choices are: %s" % (
  622. f.name,
  623. ", ".join(_get_field_choices()) or '(none)',
  624. )
  625. )
  626. else:
  627. next = False
  628. if not select_related_descend(f, restricted, requested,
  629. only_load.get(field_model)):
  630. continue
  631. klass_info = {
  632. 'model': f.remote_field.model,
  633. 'field': f,
  634. 'reverse': False,
  635. 'from_parent': False,
  636. }
  637. related_klass_infos.append(klass_info)
  638. select_fields = []
  639. _, _, _, joins, _ = self.query.setup_joins(
  640. [f.name], opts, root_alias)
  641. alias = joins[-1]
  642. columns = self.get_default_columns(start_alias=alias, opts=f.remote_field.model._meta)
  643. for col in columns:
  644. select_fields.append(len(select))
  645. select.append((col, None))
  646. klass_info['select_fields'] = select_fields
  647. next_klass_infos = self.get_related_selections(
  648. select, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted)
  649. get_related_klass_infos(klass_info, next_klass_infos)
  650. if restricted:
  651. related_fields = [
  652. (o.field, o.related_model)
  653. for o in opts.related_objects
  654. if o.field.unique and not o.many_to_many
  655. ]
  656. for f, model in related_fields:
  657. if not select_related_descend(f, restricted, requested,
  658. only_load.get(model), reverse=True):
  659. continue
  660. related_field_name = f.related_query_name()
  661. fields_found.add(related_field_name)
  662. _, _, _, joins, _ = self.query.setup_joins([related_field_name], opts, root_alias)
  663. alias = joins[-1]
  664. from_parent = issubclass(model, opts.model)
  665. klass_info = {
  666. 'model': model,
  667. 'field': f,
  668. 'reverse': True,
  669. 'from_parent': from_parent,
  670. }
  671. related_klass_infos.append(klass_info)
  672. select_fields = []
  673. columns = self.get_default_columns(
  674. start_alias=alias, opts=model._meta, from_parent=opts.model)
  675. for col in columns:
  676. select_fields.append(len(select))
  677. select.append((col, None))
  678. klass_info['select_fields'] = select_fields
  679. next = requested.get(f.related_query_name(), {})
  680. next_klass_infos = self.get_related_selections(
  681. select, model._meta, alias, cur_depth + 1,
  682. next, restricted)
  683. get_related_klass_infos(klass_info, next_klass_infos)
  684. fields_not_found = set(requested.keys()).difference(fields_found)
  685. if fields_not_found:
  686. invalid_fields = ("'%s'" % s for s in fields_not_found)
  687. raise FieldError(
  688. 'Invalid field name(s) given in select_related: %s. '
  689. 'Choices are: %s' % (
  690. ', '.join(invalid_fields),
  691. ', '.join(_get_field_choices()) or '(none)',
  692. )
  693. )
  694. return related_klass_infos
  695. def deferred_to_columns(self):
  696. """
  697. Converts the self.deferred_loading data structure to mapping of table
  698. names to sets of column names which are to be loaded. Returns the
  699. dictionary.
  700. """
  701. columns = {}
  702. self.query.deferred_to_data(columns, self.query.get_loaded_field_names_cb)
  703. return columns
  704. def get_converters(self, expressions):
  705. converters = {}
  706. for i, expression in enumerate(expressions):
  707. if expression:
  708. backend_converters = self.connection.ops.get_db_converters(expression)
  709. field_converters = expression.get_db_converters(self.connection)
  710. if backend_converters or field_converters:
  711. converters[i] = (backend_converters + field_converters, expression)
  712. return converters
  713. def apply_converters(self, row, converters):
  714. row = list(row)
  715. for pos, (convs, expression) in converters.items():
  716. value = row[pos]
  717. for converter in convs:
  718. value = converter(value, expression, self.connection, self.query.context)
  719. row[pos] = value
  720. return tuple(row)
  721. def results_iter(self, results=None):
  722. """
  723. Returns an iterator over the results from executing this query.
  724. """
  725. converters = None
  726. if results is None:
  727. results = self.execute_sql(MULTI)
  728. fields = [s[0] for s in self.select[0:self.col_count]]
  729. converters = self.get_converters(fields)
  730. for rows in results:
  731. for row in rows:
  732. if converters:
  733. row = self.apply_converters(row, converters)
  734. yield row
  735. def has_results(self):
  736. """
  737. Backends (e.g. NoSQL) can override this in order to use optimized
  738. versions of "query has any results."
  739. """
  740. # This is always executed on a query clone, so we can modify self.query
  741. self.query.add_extra({'a': 1}, None, None, None, None, None)
  742. self.query.set_extra_mask(['a'])
  743. return bool(self.execute_sql(SINGLE))
  744. def execute_sql(self, result_type=MULTI):
  745. """
  746. Run the query against the database and returns the result(s). The
  747. return value is a single data item if result_type is SINGLE, or an
  748. iterator over the results if the result_type is MULTI.
  749. result_type is either MULTI (use fetchmany() to retrieve all rows),
  750. SINGLE (only retrieve a single row), or None. In this last case, the
  751. cursor is returned if any query is executed, since it's used by
  752. subclasses such as InsertQuery). It's possible, however, that no query
  753. is needed, as the filters describe an empty set. In that case, None is
  754. returned, to avoid any unnecessary database interaction.
  755. """
  756. if not result_type:
  757. result_type = NO_RESULTS
  758. try:
  759. sql, params = self.as_sql()
  760. if not sql:
  761. raise EmptyResultSet
  762. except EmptyResultSet:
  763. if result_type == MULTI:
  764. return iter([])
  765. else:
  766. return
  767. cursor = self.connection.cursor()
  768. try:
  769. cursor.execute(sql, params)
  770. except Exception:
  771. cursor.close()
  772. raise
  773. if result_type == CURSOR:
  774. # Caller didn't specify a result_type, so just give them back the
  775. # cursor to process (and close).
  776. return cursor
  777. if result_type == SINGLE:
  778. try:
  779. val = cursor.fetchone()
  780. if val:
  781. return val[0:self.col_count]
  782. return val
  783. finally:
  784. # done with the cursor
  785. cursor.close()
  786. if result_type == NO_RESULTS:
  787. cursor.close()
  788. return
  789. result = cursor_iter(
  790. cursor, self.connection.features.empty_fetchmany_value,
  791. self.col_count
  792. )
  793. if not self.connection.features.can_use_chunked_reads:
  794. try:
  795. # If we are using non-chunked reads, we return the same data
  796. # structure as normally, but ensure it is all read into memory
  797. # before going any further.
  798. return list(result)
  799. finally:
  800. # done with the cursor
  801. cursor.close()
  802. return result
  803. def as_subquery_condition(self, alias, columns, compiler):
  804. qn = compiler.quote_name_unless_alias
  805. qn2 = self.connection.ops.quote_name
  806. if len(columns) == 1:
  807. sql, params = self.as_sql()
  808. return '%s.%s IN (%s)' % (qn(alias), qn2(columns[0]), sql), params
  809. for index, select_col in enumerate(self.query.select):
  810. lhs_sql, lhs_params = self.compile(select_col)
  811. rhs = '%s.%s' % (qn(alias), qn2(columns[index]))
  812. self.query.where.add(
  813. QueryWrapper('%s = %s' % (lhs_sql, rhs), lhs_params), 'AND')
  814. sql, params = self.as_sql()
  815. return 'EXISTS (%s)' % sql, params
  816. class SQLInsertCompiler(SQLCompiler):
  817. def __init__(self, *args, **kwargs):
  818. self.return_id = False
  819. super(SQLInsertCompiler, self).__init__(*args, **kwargs)
  820. def field_as_sql(self, field, val):
  821. """
  822. Take a field and a value intended to be saved on that field, and
  823. return placeholder SQL and accompanying params. Checks for raw values,
  824. expressions and fields with get_placeholder() defined in that order.
  825. When field is None, the value is considered raw and is used as the
  826. placeholder, with no corresponding parameters returned.
  827. """
  828. if field is None:
  829. # A field value of None means the value is raw.
  830. sql, params = val, []
  831. elif hasattr(val, 'as_sql'):
  832. # This is an expression, let's compile it.
  833. sql, params = self.compile(val)
  834. elif hasattr(field, 'get_placeholder'):
  835. # Some fields (e.g. geo fields) need special munging before
  836. # they can be inserted.
  837. sql, params = field.get_placeholder(val, self, self.connection), [val]
  838. else:
  839. # Return the common case for the placeholder
  840. sql, params = '%s', [val]
  841. # The following hook is only used by Oracle Spatial, which sometimes
  842. # needs to yield 'NULL' and [] as its placeholder and params instead
  843. # of '%s' and [None]. The 'NULL' placeholder is produced earlier by
  844. # OracleOperations.get_geom_placeholder(). The following line removes
  845. # the corresponding None parameter. See ticket #10888.
  846. params = self.connection.ops.modify_insert_params(sql, params)
  847. return sql, params
  848. def prepare_value(self, field, value):
  849. """
  850. Prepare a value to be used in a query by resolving it if it is an
  851. expression and otherwise calling the field's get_db_prep_save().
  852. """
  853. if hasattr(value, 'resolve_expression'):
  854. value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
  855. # Don't allow values containing Col expressions. They refer to
  856. # existing columns on a row, but in the case of insert the row
  857. # doesn't exist yet.
  858. if value.contains_column_references:
  859. raise ValueError(
  860. 'Failed to insert expression "%s" on %s. F() expressions '
  861. 'can only be used to update, not to insert.' % (value, field)
  862. )
  863. if value.contains_aggregate:
  864. raise FieldError("Aggregate functions are not allowed in this query")
  865. else:
  866. value = field.get_db_prep_save(value, connection=self.connection)
  867. return value
  868. def pre_save_val(self, field, obj):
  869. """
  870. Get the given field's value off the given obj. pre_save() is used for
  871. things like auto_now on DateTimeField. Skip it if this is a raw query.
  872. """
  873. if self.query.raw:
  874. return getattr(obj, field.attname)
  875. return field.pre_save(obj, add=True)
  876. def assemble_as_sql(self, fields, value_rows):
  877. """
  878. Take a sequence of N fields and a sequence of M rows of values,
  879. generate placeholder SQL and parameters for each field and value, and
  880. return a pair containing:
  881. * a sequence of M rows of N SQL placeholder strings, and
  882. * a sequence of M rows of corresponding parameter values.
  883. Each placeholder string may contain any number of '%s' interpolation
  884. strings, and each parameter row will contain exactly as many params
  885. as the total number of '%s's in the corresponding placeholder row.
  886. """
  887. if not value_rows:
  888. return [], []
  889. # list of (sql, [params]) tuples for each object to be saved
  890. # Shape: [n_objs][n_fields][2]
  891. rows_of_fields_as_sql = (
  892. (self.field_as_sql(field, v) for field, v in zip(fields, row))
  893. for row in value_rows
  894. )
  895. # tuple like ([sqls], [[params]s]) for each object to be saved
  896. # Shape: [n_objs][2][n_fields]
  897. sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql)
  898. # Extract separate lists for placeholders and params.
  899. # Each of these has shape [n_objs][n_fields]
  900. placeholder_rows, param_rows = zip(*sql_and_param_pair_rows)
  901. # Params for each field are still lists, and need to be flattened.
  902. param_rows = [[p for ps in row for p in ps] for row in param_rows]
  903. return placeholder_rows, param_rows
  904. def as_sql(self):
  905. # We don't need quote_name_unless_alias() here, since these are all
  906. # going to be column names (so we can avoid the extra overhead).
  907. qn = self.connection.ops.quote_name
  908. opts = self.query.get_meta()
  909. result = ['INSERT INTO %s' % qn(opts.db_table)]
  910. has_fields = bool(self.query.fields)
  911. fields = self.query.fields if has_fields else [opts.pk]
  912. result.append('(%s)' % ', '.join(qn(f.column) for f in fields))
  913. if has_fields:
  914. value_rows = [
  915. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  916. for obj in self.query.objs
  917. ]
  918. else:
  919. # An empty object.
  920. value_rows = [[self.connection.ops.pk_default_value()] for _ in self.query.objs]
  921. fields = [None]
  922. # Currently the backends just accept values when generating bulk
  923. # queries and generate their own placeholders. Doing that isn't
  924. # necessary and it should be possible to use placeholders and
  925. # expressions in bulk inserts too.
  926. can_bulk = (not self.return_id and self.connection.features.has_bulk_insert)
  927. placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)
  928. if self.return_id and self.connection.features.can_return_id_from_insert:
  929. params = param_rows[0]
  930. col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column))
  931. result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
  932. r_fmt, r_params = self.connection.ops.return_insert_id()
  933. # Skip empty r_fmt to allow subclasses to customize behavior for
  934. # 3rd party backends. Refs #19096.
  935. if r_fmt:
  936. result.append(r_fmt % col)
  937. params += r_params
  938. return [(" ".join(result), tuple(params))]
  939. if can_bulk:
  940. result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
  941. return [(" ".join(result), tuple(p for ps in param_rows for p in ps))]
  942. else:
  943. return [
  944. (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
  945. for p, vals in zip(placeholder_rows, param_rows)
  946. ]
  947. def execute_sql(self, return_id=False):
  948. assert not (return_id and len(self.query.objs) != 1)
  949. self.return_id = return_id
  950. with self.connection.cursor() as cursor:
  951. for sql, params in self.as_sql():
  952. cursor.execute(sql, params)
  953. if not (return_id and cursor):
  954. return
  955. if self.connection.features.can_return_id_from_insert:
  956. return self.connection.ops.fetch_returned_insert_id(cursor)
  957. return self.connection.ops.last_insert_id(cursor,
  958. self.query.get_meta().db_table, self.query.get_meta().pk.column)
  959. class SQLDeleteCompiler(SQLCompiler):
  960. def as_sql(self):
  961. """
  962. Creates the SQL for this query. Returns the SQL string and list of
  963. parameters.
  964. """
  965. assert len([t for t in self.query.tables if self.query.alias_refcount[t] > 0]) == 1, \
  966. "Can only delete from one table at a time."
  967. qn = self.quote_name_unless_alias
  968. result = ['DELETE FROM %s' % qn(self.query.tables[0])]
  969. where, params = self.compile(self.query.where)
  970. if where:
  971. result.append('WHERE %s' % where)
  972. return ' '.join(result), tuple(params)
  973. class SQLUpdateCompiler(SQLCompiler):
  974. def as_sql(self):
  975. """
  976. Creates the SQL for this query. Returns the SQL string and list of
  977. parameters.
  978. """
  979. self.pre_sql_setup()
  980. if not self.query.values:
  981. return '', ()
  982. table = self.query.tables[0]
  983. qn = self.quote_name_unless_alias
  984. result = ['UPDATE %s' % qn(table)]
  985. result.append('SET')
  986. values, update_params = [], []
  987. for field, model, val in self.query.values:
  988. if hasattr(val, 'resolve_expression'):
  989. val = val.resolve_expression(self.query, allow_joins=False, for_save=True)
  990. if val.contains_aggregate:
  991. raise FieldError("Aggregate functions are not allowed in this query")
  992. elif hasattr(val, 'prepare_database_save'):
  993. if field.remote_field:
  994. val = field.get_db_prep_save(
  995. val.prepare_database_save(field),
  996. connection=self.connection,
  997. )
  998. else:
  999. raise TypeError(
  1000. "Tried to update field %s with a model instance, %r. "
  1001. "Use a value compatible with %s."
  1002. % (field, val, field.__class__.__name__)
  1003. )
  1004. else:
  1005. val = field.get_db_prep_save(val, connection=self.connection)
  1006. # Getting the placeholder for the field.
  1007. if hasattr(field, 'get_placeholder'):
  1008. placeholder = field.get_placeholder(val, self, self.connection)
  1009. else:
  1010. placeholder = '%s'
  1011. name = field.column
  1012. if hasattr(val, 'as_sql'):
  1013. sql, params = self.compile(val)
  1014. values.append('%s = %s' % (qn(name), sql))
  1015. update_params.extend(params)
  1016. elif val is not None:
  1017. values.append('%s = %s' % (qn(name), placeholder))
  1018. update_params.append(val)
  1019. else:
  1020. values.append('%s = NULL' % qn(name))
  1021. if not values:
  1022. return '', ()
  1023. result.append(', '.join(values))
  1024. where, params = self.compile(self.query.where)
  1025. if where:
  1026. result.append('WHERE %s' % where)
  1027. return ' '.join(result), tuple(update_params + params)
  1028. def execute_sql(self, result_type):
  1029. """
  1030. Execute the specified update. Returns the number of rows affected by
  1031. the primary update query. The "primary update query" is the first
  1032. non-empty query that is executed. Row counts for any subsequent,
  1033. related queries are not available.
  1034. """
  1035. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  1036. try:
  1037. rows = cursor.rowcount if cursor else 0
  1038. is_empty = cursor is None
  1039. finally:
  1040. if cursor:
  1041. cursor.close()
  1042. for query in self.query.get_related_updates():
  1043. aux_rows = query.get_compiler(self.using).execute_sql(result_type)
  1044. if is_empty and aux_rows:
  1045. rows = aux_rows
  1046. is_empty = False
  1047. return rows
  1048. def pre_sql_setup(self):
  1049. """
  1050. If the update depends on results from other tables, we need to do some
  1051. munging of the "where" conditions to match the format required for
  1052. (portable) SQL updates. That is done here.
  1053. Further, if we are going to be running multiple updates, we pull out
  1054. the id values to update at this point so that they don't change as a
  1055. result of the progressive updates.
  1056. """
  1057. refcounts_before = self.query.alias_refcount.copy()
  1058. # Ensure base table is in the query
  1059. self.query.get_initial_alias()
  1060. count = self.query.count_active_tables()
  1061. if not self.query.related_updates and count == 1:
  1062. return
  1063. query = self.query.clone(klass=Query)
  1064. query.select_related = False
  1065. query.clear_ordering(True)
  1066. query._extra = {}
  1067. query.select = []
  1068. query.add_fields([query.get_meta().pk.name])
  1069. super(SQLUpdateCompiler, self).pre_sql_setup()
  1070. must_pre_select = count > 1 and not self.connection.features.update_can_self_select
  1071. # Now we adjust the current query: reset the where clause and get rid
  1072. # of all the tables we don't need (since they're in the sub-select).
  1073. self.query.where = self.query.where_class()
  1074. if self.query.related_updates or must_pre_select:
  1075. # Either we're using the idents in multiple update queries (so
  1076. # don't want them to change), or the db backend doesn't support
  1077. # selecting from the updating table (e.g. MySQL).
  1078. idents = []
  1079. for rows in query.get_compiler(self.using).execute_sql(MULTI):
  1080. idents.extend(r[0] for r in rows)
  1081. self.query.add_filter(('pk__in', idents))
  1082. self.query.related_ids = idents
  1083. else:
  1084. # The fast path. Filters and updates in one query.
  1085. self.query.add_filter(('pk__in', query))
  1086. self.query.reset_refcounts(refcounts_before)
  1087. class SQLAggregateCompiler(SQLCompiler):
  1088. def as_sql(self):
  1089. """
  1090. Creates the SQL for this query. Returns the SQL string and list of
  1091. parameters.
  1092. """
  1093. # Empty SQL for the inner query is a marker that the inner query
  1094. # isn't going to produce any results. This can happen when doing
  1095. # LIMIT 0 queries (generated by qs[:0]) for example.
  1096. if not self.query.subquery:
  1097. raise EmptyResultSet
  1098. sql, params = [], []
  1099. for annotation in self.query.annotation_select.values():
  1100. ann_sql, ann_params = self.compile(annotation, select_format=True)
  1101. sql.append(ann_sql)
  1102. params.extend(ann_params)
  1103. self.col_count = len(self.query.annotation_select)
  1104. sql = ', '.join(sql)
  1105. params = tuple(params)
  1106. sql = 'SELECT %s FROM (%s) subquery' % (sql, self.query.subquery)
  1107. params = params + self.query.sub_params
  1108. return sql, params
  1109. def cursor_iter(cursor, sentinel, col_count):
  1110. """
  1111. Yields blocks of rows from a cursor and ensures the cursor is closed when
  1112. done.
  1113. """
  1114. try:
  1115. for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
  1116. sentinel):
  1117. yield [r[0:col_count] for r in rows]
  1118. finally:
  1119. cursor.close()