compiler.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  1. import collections
  2. import re
  3. from functools import partial
  4. from itertools import chain
  5. from django.core.exceptions import EmptyResultSet, FieldError
  6. from django.db.models.constants import LOOKUP_SEP
  7. from django.db.models.expressions import OrderBy, Random, RawSQL, Ref, Value
  8. from django.db.models.functions import Cast
  9. from django.db.models.query_utils import Q, select_related_descend
  10. from django.db.models.sql.constants import (
  11. CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE,
  12. )
  13. from django.db.models.sql.query import Query, get_order_dir
  14. from django.db.transaction import TransactionManagementError
  15. from django.db.utils import DatabaseError, NotSupportedError
  16. from django.utils.functional import cached_property
  17. from django.utils.hashable import make_hashable
  18. class SQLCompiler:
  19. def __init__(self, query, connection, using):
  20. self.query = query
  21. self.connection = connection
  22. self.using = using
  23. self.quote_cache = {'*': '*'}
  24. # The select, klass_info, and annotations are needed by QuerySet.iterator()
  25. # these are set as a side-effect of executing the query. Note that we calculate
  26. # separately a list of extra select columns needed for grammatical correctness
  27. # of the query, but these columns are not included in self.select.
  28. self.select = None
  29. self.annotation_col_map = None
  30. self.klass_info = None
  31. # Multiline ordering SQL clause may appear from RawSQL.
  32. self.ordering_parts = re.compile(r'^(.*)\s(ASC|DESC)(.*)', re.MULTILINE | re.DOTALL)
  33. self._meta_ordering = None
  34. def setup_query(self):
  35. if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map):
  36. self.query.get_initial_alias()
  37. self.select, self.klass_info, self.annotation_col_map = self.get_select()
  38. self.col_count = len(self.select)
  39. def pre_sql_setup(self):
  40. """
  41. Do any necessary class setup immediately prior to producing SQL. This
  42. is for things that can't necessarily be done in __init__ because we
  43. might not have all the pieces in place at that time.
  44. """
  45. self.setup_query()
  46. order_by = self.get_order_by()
  47. self.where, self.having = self.query.where.split_having()
  48. extra_select = self.get_extra_select(order_by, self.select)
  49. self.has_extra_select = bool(extra_select)
  50. group_by = self.get_group_by(self.select + extra_select, order_by)
  51. return extra_select, order_by, group_by
  52. def get_group_by(self, select, order_by):
  53. """
  54. Return a list of 2-tuples of form (sql, params).
  55. The logic of what exactly the GROUP BY clause contains is hard
  56. to describe in other words than "if it passes the test suite,
  57. then it is correct".
  58. """
  59. # Some examples:
  60. # SomeModel.objects.annotate(Count('somecol'))
  61. # GROUP BY: all fields of the model
  62. #
  63. # SomeModel.objects.values('name').annotate(Count('somecol'))
  64. # GROUP BY: name
  65. #
  66. # SomeModel.objects.annotate(Count('somecol')).values('name')
  67. # GROUP BY: all cols of the model
  68. #
  69. # SomeModel.objects.values('name', 'pk').annotate(Count('somecol')).values('pk')
  70. # GROUP BY: name, pk
  71. #
  72. # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk')
  73. # GROUP BY: name, pk
  74. #
  75. # In fact, the self.query.group_by is the minimal set to GROUP BY. It
  76. # can't be ever restricted to a smaller set, but additional columns in
  77. # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately
  78. # the end result is that it is impossible to force the query to have
  79. # a chosen GROUP BY clause - you can almost do this by using the form:
  80. # .values(*wanted_cols).annotate(AnAggregate())
  81. # but any later annotations, extra selects, values calls that
  82. # refer some column outside of the wanted_cols, order_by, or even
  83. # filter calls can alter the GROUP BY clause.
  84. # The query.group_by is either None (no GROUP BY at all), True
  85. # (group by select fields), or a list of expressions to be added
  86. # to the group by.
  87. if self.query.group_by is None:
  88. return []
  89. expressions = []
  90. if self.query.group_by is not True:
  91. # If the group by is set to a list (by .values() call most likely),
  92. # then we need to add everything in it to the GROUP BY clause.
  93. # Backwards compatibility hack for setting query.group_by. Remove
  94. # when we have public API way of forcing the GROUP BY clause.
  95. # Converts string references to expressions.
  96. for expr in self.query.group_by:
  97. if not hasattr(expr, 'as_sql'):
  98. expressions.append(self.query.resolve_ref(expr))
  99. else:
  100. expressions.append(expr)
  101. # Note that even if the group_by is set, it is only the minimal
  102. # set to group by. So, we need to add cols in select, order_by, and
  103. # having into the select in any case.
  104. for expr, _, _ in select:
  105. cols = expr.get_group_by_cols()
  106. for col in cols:
  107. expressions.append(col)
  108. for expr, (sql, params, is_ref) in order_by:
  109. # Skip References to the select clause, as all expressions in the
  110. # select clause are already part of the group by.
  111. if not expr.contains_aggregate and not is_ref:
  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. params_hash = make_hashable(params)
  122. if (sql, params_hash) not in seen:
  123. result.append((sql, params))
  124. seen.add((sql, params_hash))
  125. return result
  126. def collapse_group_by(self, expressions, having):
  127. # If the DB can group by primary key, then group by the primary key of
  128. # query's main model. Note that for PostgreSQL the GROUP BY clause must
  129. # include the primary key of every table, but for MySQL it is enough to
  130. # have the main table's primary key.
  131. if self.connection.features.allows_group_by_pk:
  132. # Determine if the main model's primary key is in the query.
  133. pk = None
  134. for expr in expressions:
  135. # Is this a reference to query's base table primary key? If the
  136. # expression isn't a Col-like, then skip the expression.
  137. if (getattr(expr, 'target', None) == self.query.model._meta.pk and
  138. getattr(expr, 'alias', None) == self.query.base_table):
  139. pk = expr
  140. break
  141. # If the main model's primary key is in the query, group by that
  142. # field, HAVING expressions, and expressions associated with tables
  143. # that don't have a primary key included in the grouped columns.
  144. if pk:
  145. pk_aliases = {
  146. expr.alias for expr in expressions
  147. if hasattr(expr, 'target') and expr.target.primary_key
  148. }
  149. expressions = [pk] + [
  150. expr for expr in expressions
  151. if expr in having or (
  152. getattr(expr, 'alias', None) is not None and expr.alias not in pk_aliases
  153. )
  154. ]
  155. elif self.connection.features.allows_group_by_selected_pks:
  156. # Filter out all expressions associated with a table's primary key
  157. # present in the grouped columns. This is done by identifying all
  158. # tables that have their primary key included in the grouped
  159. # columns and removing non-primary key columns referring to them.
  160. # Unmanaged models are excluded because they could be representing
  161. # database views on which the optimization might not be allowed.
  162. pks = {
  163. expr for expr in expressions
  164. if (
  165. hasattr(expr, 'target') and
  166. expr.target.primary_key and
  167. self.connection.features.allows_group_by_selected_pks_on_model(expr.target.model)
  168. )
  169. }
  170. aliases = {expr.alias for expr in pks}
  171. expressions = [
  172. expr for expr in expressions if expr in pks or getattr(expr, 'alias', None) not in aliases
  173. ]
  174. return expressions
  175. def get_select(self):
  176. """
  177. Return three values:
  178. - a list of 3-tuples of (expression, (sql, params), alias)
  179. - a klass_info structure,
  180. - a dictionary of annotations
  181. The (sql, params) is what the expression will produce, and alias is the
  182. "AS alias" for the column (possibly None).
  183. The klass_info structure contains the following information:
  184. - The base model of the query.
  185. - Which columns for that model are present in the query (by
  186. position of the select clause).
  187. - related_klass_infos: [f, klass_info] to descent into
  188. The annotations is a dictionary of {'attname': column position} values.
  189. """
  190. select = []
  191. klass_info = None
  192. annotations = {}
  193. select_idx = 0
  194. for alias, (sql, params) in self.query.extra_select.items():
  195. annotations[alias] = select_idx
  196. select.append((RawSQL(sql, params), alias))
  197. select_idx += 1
  198. assert not (self.query.select and self.query.default_cols)
  199. if self.query.default_cols:
  200. cols = self.get_default_columns()
  201. else:
  202. # self.query.select is a special case. These columns never go to
  203. # any model.
  204. cols = self.query.select
  205. if cols:
  206. select_list = []
  207. for col in cols:
  208. select_list.append(select_idx)
  209. select.append((col, None))
  210. select_idx += 1
  211. klass_info = {
  212. 'model': self.query.model,
  213. 'select_fields': select_list,
  214. }
  215. for alias, annotation in self.query.annotation_select.items():
  216. annotations[alias] = select_idx
  217. select.append((annotation, alias))
  218. select_idx += 1
  219. if self.query.select_related:
  220. related_klass_infos = self.get_related_selections(select)
  221. klass_info['related_klass_infos'] = related_klass_infos
  222. def get_select_from_parent(klass_info):
  223. for ki in klass_info['related_klass_infos']:
  224. if ki['from_parent']:
  225. ki['select_fields'] = (klass_info['select_fields'] +
  226. ki['select_fields'])
  227. get_select_from_parent(ki)
  228. get_select_from_parent(klass_info)
  229. ret = []
  230. for col, alias in select:
  231. try:
  232. sql, params = self.compile(col)
  233. except EmptyResultSet:
  234. # Select a predicate that's always False.
  235. sql, params = '0', ()
  236. else:
  237. sql, params = col.select_format(self, sql, params)
  238. ret.append((col, (sql, params), alias))
  239. return ret, klass_info, annotations
  240. def get_order_by(self):
  241. """
  242. Return a list of 2-tuples of form (expr, (sql, params, is_ref)) for the
  243. ORDER BY clause.
  244. The order_by clause can alter the select clause (for example it
  245. can add aliases to clauses that do not yet have one, or it can
  246. add totally new select clauses).
  247. """
  248. if self.query.extra_order_by:
  249. ordering = self.query.extra_order_by
  250. elif not self.query.default_ordering:
  251. ordering = self.query.order_by
  252. elif self.query.order_by:
  253. ordering = self.query.order_by
  254. elif self.query.get_meta().ordering:
  255. ordering = self.query.get_meta().ordering
  256. self._meta_ordering = ordering
  257. else:
  258. ordering = []
  259. if self.query.standard_ordering:
  260. asc, desc = ORDER_DIR['ASC']
  261. else:
  262. asc, desc = ORDER_DIR['DESC']
  263. order_by = []
  264. for field in ordering:
  265. if hasattr(field, 'resolve_expression'):
  266. if isinstance(field, Value):
  267. # output_field must be resolved for constants.
  268. field = Cast(field, field.output_field)
  269. if not isinstance(field, OrderBy):
  270. field = field.asc()
  271. if not self.query.standard_ordering:
  272. field = field.copy()
  273. field.reverse_ordering()
  274. order_by.append((field, False))
  275. continue
  276. if field == '?': # random
  277. order_by.append((OrderBy(Random()), False))
  278. continue
  279. col, order = get_order_dir(field, asc)
  280. descending = order == 'DESC'
  281. if col in self.query.annotation_select:
  282. # Reference to expression in SELECT clause
  283. order_by.append((
  284. OrderBy(Ref(col, self.query.annotation_select[col]), descending=descending),
  285. True))
  286. continue
  287. if col in self.query.annotations:
  288. # References to an expression which is masked out of the SELECT
  289. # clause.
  290. expr = self.query.annotations[col]
  291. if isinstance(expr, Value):
  292. # output_field must be resolved for constants.
  293. expr = Cast(expr, expr.output_field)
  294. order_by.append((OrderBy(expr, descending=descending), False))
  295. continue
  296. if '.' in field:
  297. # This came in through an extra(order_by=...) addition. Pass it
  298. # on verbatim.
  299. table, col = col.split('.', 1)
  300. order_by.append((
  301. OrderBy(
  302. RawSQL('%s.%s' % (self.quote_name_unless_alias(table), col), []),
  303. descending=descending
  304. ), False))
  305. continue
  306. if not self.query.extra or col not in self.query.extra:
  307. # 'col' is of the form 'field' or 'field1__field2' or
  308. # '-field1__field2__field', etc.
  309. order_by.extend(self.find_ordering_name(
  310. field, self.query.get_meta(), default_order=asc))
  311. else:
  312. if col not in self.query.extra_select:
  313. order_by.append((
  314. OrderBy(RawSQL(*self.query.extra[col]), descending=descending),
  315. False))
  316. else:
  317. order_by.append((
  318. OrderBy(Ref(col, RawSQL(*self.query.extra[col])), descending=descending),
  319. True))
  320. result = []
  321. seen = set()
  322. for expr, is_ref in order_by:
  323. resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
  324. if self.query.combinator:
  325. src = resolved.get_source_expressions()[0]
  326. # Relabel order by columns to raw numbers if this is a combined
  327. # query; necessary since the columns can't be referenced by the
  328. # fully qualified name and the simple column names may collide.
  329. for idx, (sel_expr, _, col_alias) in enumerate(self.select):
  330. if is_ref and col_alias == src.refs:
  331. src = src.source
  332. elif col_alias:
  333. continue
  334. if src == sel_expr:
  335. resolved.set_source_expressions([RawSQL('%d' % (idx + 1), ())])
  336. break
  337. else:
  338. if col_alias:
  339. raise DatabaseError('ORDER BY term does not match any column in the result set.')
  340. # Add column used in ORDER BY clause without an alias to
  341. # the selected columns.
  342. self.query.add_select_col(src)
  343. resolved.set_source_expressions([RawSQL('%d' % len(self.query.select), ())])
  344. sql, params = self.compile(resolved)
  345. # Don't add the same column twice, but the order direction is
  346. # not taken into account so we strip it. When this entire method
  347. # is refactored into expressions, then we can check each part as we
  348. # generate it.
  349. without_ordering = self.ordering_parts.search(sql).group(1)
  350. params_hash = make_hashable(params)
  351. if (without_ordering, params_hash) in seen:
  352. continue
  353. seen.add((without_ordering, params_hash))
  354. result.append((resolved, (sql, params, is_ref)))
  355. return result
  356. def get_extra_select(self, order_by, select):
  357. extra_select = []
  358. if self.query.distinct and not self.query.distinct_fields:
  359. select_sql = [t[1] for t in select]
  360. for expr, (sql, params, is_ref) in order_by:
  361. without_ordering = self.ordering_parts.search(sql).group(1)
  362. if not is_ref and (without_ordering, params) not in select_sql:
  363. extra_select.append((expr, (without_ordering, params), None))
  364. return extra_select
  365. def quote_name_unless_alias(self, name):
  366. """
  367. A wrapper around connection.ops.quote_name that doesn't quote aliases
  368. for table names. This avoids problems with some SQL dialects that treat
  369. quoted strings specially (e.g. PostgreSQL).
  370. """
  371. if name in self.quote_cache:
  372. return self.quote_cache[name]
  373. if ((name in self.query.alias_map and name not in self.query.table_map) or
  374. name in self.query.extra_select or (
  375. name in self.query.external_aliases and name not in self.query.table_map)):
  376. self.quote_cache[name] = name
  377. return name
  378. r = self.connection.ops.quote_name(name)
  379. self.quote_cache[name] = r
  380. return r
  381. def compile(self, node):
  382. vendor_impl = getattr(node, 'as_' + self.connection.vendor, None)
  383. if vendor_impl:
  384. sql, params = vendor_impl(self, self.connection)
  385. else:
  386. sql, params = node.as_sql(self, self.connection)
  387. return sql, params
  388. def get_combinator_sql(self, combinator, all):
  389. features = self.connection.features
  390. compilers = [
  391. query.get_compiler(self.using, self.connection)
  392. for query in self.query.combined_queries if not query.is_empty()
  393. ]
  394. if not features.supports_slicing_ordering_in_compound:
  395. for query, compiler in zip(self.query.combined_queries, compilers):
  396. if query.low_mark or query.high_mark:
  397. raise DatabaseError('LIMIT/OFFSET not allowed in subqueries of compound statements.')
  398. if compiler.get_order_by():
  399. raise DatabaseError('ORDER BY not allowed in subqueries of compound statements.')
  400. parts = ()
  401. for compiler in compilers:
  402. try:
  403. # If the columns list is limited, then all combined queries
  404. # must have the same columns list. Set the selects defined on
  405. # the query on all combined queries, if not already set.
  406. if not compiler.query.values_select and self.query.values_select:
  407. compiler.query = compiler.query.clone()
  408. compiler.query.set_values((
  409. *self.query.extra_select,
  410. *self.query.values_select,
  411. *self.query.annotation_select,
  412. ))
  413. part_sql, part_args = compiler.as_sql()
  414. if compiler.query.combinator:
  415. # Wrap in a subquery if wrapping in parentheses isn't
  416. # supported.
  417. if not features.supports_parentheses_in_compound:
  418. part_sql = 'SELECT * FROM ({})'.format(part_sql)
  419. # Add parentheses when combining with compound query if not
  420. # already added for all compound queries.
  421. elif not features.supports_slicing_ordering_in_compound:
  422. part_sql = '({})'.format(part_sql)
  423. parts += ((part_sql, part_args),)
  424. except EmptyResultSet:
  425. # Omit the empty queryset with UNION and with DIFFERENCE if the
  426. # first queryset is nonempty.
  427. if combinator == 'union' or (combinator == 'difference' and parts):
  428. continue
  429. raise
  430. if not parts:
  431. raise EmptyResultSet
  432. combinator_sql = self.connection.ops.set_operators[combinator]
  433. if all and combinator == 'union':
  434. combinator_sql += ' ALL'
  435. braces = '({})' if features.supports_slicing_ordering_in_compound else '{}'
  436. sql_parts, args_parts = zip(*((braces.format(sql), args) for sql, args in parts))
  437. result = [' {} '.format(combinator_sql).join(sql_parts)]
  438. params = []
  439. for part in args_parts:
  440. params.extend(part)
  441. return result, params
  442. def as_sql(self, with_limits=True, with_col_aliases=False):
  443. """
  444. Create the SQL for this query. Return the SQL string and list of
  445. parameters.
  446. If 'with_limits' is False, any limit/offset information is not included
  447. in the query.
  448. """
  449. refcounts_before = self.query.alias_refcount.copy()
  450. try:
  451. extra_select, order_by, group_by = self.pre_sql_setup()
  452. for_update_part = None
  453. # Is a LIMIT/OFFSET clause needed?
  454. with_limit_offset = with_limits and (self.query.high_mark is not None or self.query.low_mark)
  455. combinator = self.query.combinator
  456. features = self.connection.features
  457. if combinator:
  458. if not getattr(features, 'supports_select_{}'.format(combinator)):
  459. raise NotSupportedError('{} is not supported on this database backend.'.format(combinator))
  460. result, params = self.get_combinator_sql(combinator, self.query.combinator_all)
  461. else:
  462. distinct_fields, distinct_params = self.get_distinct()
  463. # This must come after 'select', 'ordering', and 'distinct'
  464. # (see docstring of get_from_clause() for details).
  465. from_, f_params = self.get_from_clause()
  466. where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  467. having, h_params = self.compile(self.having) if self.having is not None else ("", [])
  468. result = ['SELECT']
  469. params = []
  470. if self.query.distinct:
  471. distinct_result, distinct_params = self.connection.ops.distinct_sql(
  472. distinct_fields,
  473. distinct_params,
  474. )
  475. result += distinct_result
  476. params += distinct_params
  477. out_cols = []
  478. col_idx = 1
  479. for _, (s_sql, s_params), alias in self.select + extra_select:
  480. if alias:
  481. s_sql = '%s AS %s' % (s_sql, self.connection.ops.quote_name(alias))
  482. elif with_col_aliases:
  483. s_sql = '%s AS %s' % (s_sql, 'Col%d' % col_idx)
  484. col_idx += 1
  485. params.extend(s_params)
  486. out_cols.append(s_sql)
  487. result += [', '.join(out_cols), 'FROM', *from_]
  488. params.extend(f_params)
  489. if self.query.select_for_update and self.connection.features.has_select_for_update:
  490. if self.connection.get_autocommit():
  491. raise TransactionManagementError('select_for_update cannot be used outside of a transaction.')
  492. if with_limit_offset and not self.connection.features.supports_select_for_update_with_limit:
  493. raise NotSupportedError(
  494. 'LIMIT/OFFSET is not supported with '
  495. 'select_for_update on this database backend.'
  496. )
  497. nowait = self.query.select_for_update_nowait
  498. skip_locked = self.query.select_for_update_skip_locked
  499. of = self.query.select_for_update_of
  500. # If it's a NOWAIT/SKIP LOCKED/OF query but the backend
  501. # doesn't support it, raise NotSupportedError to prevent a
  502. # possible deadlock.
  503. if nowait and not self.connection.features.has_select_for_update_nowait:
  504. raise NotSupportedError('NOWAIT is not supported on this database backend.')
  505. elif skip_locked and not self.connection.features.has_select_for_update_skip_locked:
  506. raise NotSupportedError('SKIP LOCKED is not supported on this database backend.')
  507. elif of and not self.connection.features.has_select_for_update_of:
  508. raise NotSupportedError('FOR UPDATE OF is not supported on this database backend.')
  509. for_update_part = self.connection.ops.for_update_sql(
  510. nowait=nowait,
  511. skip_locked=skip_locked,
  512. of=self.get_select_for_update_of_arguments(),
  513. )
  514. if for_update_part and self.connection.features.for_update_after_from:
  515. result.append(for_update_part)
  516. if where:
  517. result.append('WHERE %s' % where)
  518. params.extend(w_params)
  519. grouping = []
  520. for g_sql, g_params in group_by:
  521. grouping.append(g_sql)
  522. params.extend(g_params)
  523. if grouping:
  524. if distinct_fields:
  525. raise NotImplementedError('annotate() + distinct(fields) is not implemented.')
  526. order_by = order_by or self.connection.ops.force_no_ordering()
  527. result.append('GROUP BY %s' % ', '.join(grouping))
  528. if self._meta_ordering:
  529. order_by = None
  530. if having:
  531. result.append('HAVING %s' % having)
  532. params.extend(h_params)
  533. if self.query.explain_query:
  534. result.insert(0, self.connection.ops.explain_query_prefix(
  535. self.query.explain_format,
  536. **self.query.explain_options
  537. ))
  538. if order_by:
  539. ordering = []
  540. for _, (o_sql, o_params, _) in order_by:
  541. ordering.append(o_sql)
  542. params.extend(o_params)
  543. result.append('ORDER BY %s' % ', '.join(ordering))
  544. if with_limit_offset:
  545. result.append(self.connection.ops.limit_offset_sql(self.query.low_mark, self.query.high_mark))
  546. if for_update_part and not self.connection.features.for_update_after_from:
  547. result.append(for_update_part)
  548. if self.query.subquery and extra_select:
  549. # If the query is used as a subquery, the extra selects would
  550. # result in more columns than the left-hand side expression is
  551. # expecting. This can happen when a subquery uses a combination
  552. # of order_by() and distinct(), forcing the ordering expressions
  553. # to be selected as well. Wrap the query in another subquery
  554. # to exclude extraneous selects.
  555. sub_selects = []
  556. sub_params = []
  557. for index, (select, _, alias) in enumerate(self.select, start=1):
  558. if not alias and with_col_aliases:
  559. alias = 'col%d' % index
  560. if alias:
  561. sub_selects.append("%s.%s" % (
  562. self.connection.ops.quote_name('subquery'),
  563. self.connection.ops.quote_name(alias),
  564. ))
  565. else:
  566. select_clone = select.relabeled_clone({select.alias: 'subquery'})
  567. subselect, subparams = select_clone.as_sql(self, self.connection)
  568. sub_selects.append(subselect)
  569. sub_params.extend(subparams)
  570. return 'SELECT %s FROM (%s) subquery' % (
  571. ', '.join(sub_selects),
  572. ' '.join(result),
  573. ), tuple(sub_params + params)
  574. return ' '.join(result), tuple(params)
  575. finally:
  576. # Finally do cleanup - get rid of the joins we created above.
  577. self.query.reset_refcounts(refcounts_before)
  578. def get_default_columns(self, start_alias=None, opts=None, from_parent=None):
  579. """
  580. Compute the default columns for selecting every field in the base
  581. model. Will sometimes be called to pull in related models (e.g. via
  582. select_related), in which case "opts" and "start_alias" will be given
  583. to provide a starting point for the traversal.
  584. Return a list of strings, quoted appropriately for use in SQL
  585. directly, as well as a set of aliases used in the select statement (if
  586. 'as_pairs' is True, return a list of (alias, col_name) pairs instead
  587. of strings as the first component and None as the second component).
  588. """
  589. result = []
  590. if opts is None:
  591. opts = self.query.get_meta()
  592. only_load = self.deferred_to_columns()
  593. start_alias = start_alias or self.query.get_initial_alias()
  594. # The 'seen_models' is used to optimize checking the needed parent
  595. # alias for a given field. This also includes None -> start_alias to
  596. # be used by local fields.
  597. seen_models = {None: start_alias}
  598. for field in opts.concrete_fields:
  599. model = field.model._meta.concrete_model
  600. # A proxy model will have a different model and concrete_model. We
  601. # will assign None if the field belongs to this model.
  602. if model == opts.model:
  603. model = None
  604. if from_parent and model is not None and issubclass(
  605. from_parent._meta.concrete_model, model._meta.concrete_model):
  606. # Avoid loading data for already loaded parents.
  607. # We end up here in the case select_related() resolution
  608. # proceeds from parent model to child model. In that case the
  609. # parent model data is already present in the SELECT clause,
  610. # and we want to avoid reloading the same data again.
  611. continue
  612. if field.model in only_load and field.attname not in only_load[field.model]:
  613. continue
  614. alias = self.query.join_parent_model(opts, model, start_alias,
  615. seen_models)
  616. column = field.get_col(alias)
  617. result.append(column)
  618. return result
  619. def get_distinct(self):
  620. """
  621. Return a quoted list of fields to use in DISTINCT ON part of the query.
  622. This method can alter the tables in the query, and thus it must be
  623. called before get_from_clause().
  624. """
  625. result = []
  626. params = []
  627. opts = self.query.get_meta()
  628. for name in self.query.distinct_fields:
  629. parts = name.split(LOOKUP_SEP)
  630. _, targets, alias, joins, path, _, transform_function = self._setup_joins(parts, opts, None)
  631. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  632. for target in targets:
  633. if name in self.query.annotation_select:
  634. result.append(name)
  635. else:
  636. r, p = self.compile(transform_function(target, alias))
  637. result.append(r)
  638. params.append(p)
  639. return result, params
  640. def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
  641. already_seen=None):
  642. """
  643. Return the table alias (the name might be ambiguous, the alias will
  644. not be) and column name for ordering by the given 'name' parameter.
  645. The 'name' is of the form 'field1__field2__...__fieldN'.
  646. """
  647. name, order = get_order_dir(name, default_order)
  648. descending = order == 'DESC'
  649. pieces = name.split(LOOKUP_SEP)
  650. field, targets, alias, joins, path, opts, transform_function = self._setup_joins(pieces, opts, alias)
  651. # If we get to this point and the field is a relation to another model,
  652. # append the default ordering for that model unless the attribute name
  653. # of the field is specified.
  654. if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name:
  655. # Firstly, avoid infinite loops.
  656. already_seen = already_seen or set()
  657. join_tuple = tuple(getattr(self.query.alias_map[j], 'join_cols', None) for j in joins)
  658. if join_tuple in already_seen:
  659. raise FieldError('Infinite loop caused by ordering.')
  660. already_seen.add(join_tuple)
  661. results = []
  662. for item in opts.ordering:
  663. if hasattr(item, 'resolve_expression') and not isinstance(item, OrderBy):
  664. item = item.desc() if descending else item.asc()
  665. if isinstance(item, OrderBy):
  666. results.append((item, False))
  667. continue
  668. results.extend(self.find_ordering_name(item, opts, alias,
  669. order, already_seen))
  670. return results
  671. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  672. return [(OrderBy(transform_function(t, alias), descending=descending), False) for t in targets]
  673. def _setup_joins(self, pieces, opts, alias):
  674. """
  675. Helper method for get_order_by() and get_distinct().
  676. get_ordering() and get_distinct() must produce same target columns on
  677. same input, as the prefixes of get_ordering() and get_distinct() must
  678. match. Executing SQL where this is not true is an error.
  679. """
  680. alias = alias or self.query.get_initial_alias()
  681. field, targets, opts, joins, path, transform_function = self.query.setup_joins(pieces, opts, alias)
  682. alias = joins[-1]
  683. return field, targets, alias, joins, path, opts, transform_function
  684. def get_from_clause(self):
  685. """
  686. Return a list of strings that are joined together to go after the
  687. "FROM" part of the query, as well as a list any extra parameters that
  688. need to be included. Subclasses, can override this to create a
  689. from-clause via a "select".
  690. This should only be called after any SQL construction methods that
  691. might change the tables that are needed. This means the select columns,
  692. ordering, and distinct must be done first.
  693. """
  694. result = []
  695. params = []
  696. for alias in tuple(self.query.alias_map):
  697. if not self.query.alias_refcount[alias]:
  698. continue
  699. try:
  700. from_clause = self.query.alias_map[alias]
  701. except KeyError:
  702. # Extra tables can end up in self.tables, but not in the
  703. # alias_map if they aren't in a join. That's OK. We skip them.
  704. continue
  705. clause_sql, clause_params = self.compile(from_clause)
  706. result.append(clause_sql)
  707. params.extend(clause_params)
  708. for t in self.query.extra_tables:
  709. alias, _ = self.query.table_alias(t)
  710. # Only add the alias if it's not already present (the table_alias()
  711. # call increments the refcount, so an alias refcount of one means
  712. # this is the only reference).
  713. if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1:
  714. result.append(', %s' % self.quote_name_unless_alias(alias))
  715. return result, params
  716. def get_related_selections(self, select, opts=None, root_alias=None, cur_depth=1,
  717. requested=None, restricted=None):
  718. """
  719. Fill in the information needed for a select_related query. The current
  720. depth is measured as the number of connections away from the root model
  721. (for example, cur_depth=1 means we are looking at models with direct
  722. connections to the root model).
  723. """
  724. def _get_field_choices():
  725. direct_choices = (f.name for f in opts.fields if f.is_relation)
  726. reverse_choices = (
  727. f.field.related_query_name()
  728. for f in opts.related_objects if f.field.unique
  729. )
  730. return chain(direct_choices, reverse_choices, self.query._filtered_relations)
  731. related_klass_infos = []
  732. if not restricted and cur_depth > self.query.max_depth:
  733. # We've recursed far enough; bail out.
  734. return related_klass_infos
  735. if not opts:
  736. opts = self.query.get_meta()
  737. root_alias = self.query.get_initial_alias()
  738. only_load = self.query.get_loaded_field_names()
  739. # Setup for the case when only particular related fields should be
  740. # included in the related selection.
  741. fields_found = set()
  742. if requested is None:
  743. restricted = isinstance(self.query.select_related, dict)
  744. if restricted:
  745. requested = self.query.select_related
  746. def get_related_klass_infos(klass_info, related_klass_infos):
  747. klass_info['related_klass_infos'] = related_klass_infos
  748. for f in opts.fields:
  749. field_model = f.model._meta.concrete_model
  750. fields_found.add(f.name)
  751. if restricted:
  752. next = requested.get(f.name, {})
  753. if not f.is_relation:
  754. # If a non-related field is used like a relation,
  755. # or if a single non-relational field is given.
  756. if next or f.name in requested:
  757. raise FieldError(
  758. "Non-relational field given in select_related: '%s'. "
  759. "Choices are: %s" % (
  760. f.name,
  761. ", ".join(_get_field_choices()) or '(none)',
  762. )
  763. )
  764. else:
  765. next = False
  766. if not select_related_descend(f, restricted, requested,
  767. only_load.get(field_model)):
  768. continue
  769. klass_info = {
  770. 'model': f.remote_field.model,
  771. 'field': f,
  772. 'reverse': False,
  773. 'local_setter': f.set_cached_value,
  774. 'remote_setter': f.remote_field.set_cached_value if f.unique else lambda x, y: None,
  775. 'from_parent': False,
  776. }
  777. related_klass_infos.append(klass_info)
  778. select_fields = []
  779. _, _, _, joins, _, _ = self.query.setup_joins(
  780. [f.name], opts, root_alias)
  781. alias = joins[-1]
  782. columns = self.get_default_columns(start_alias=alias, opts=f.remote_field.model._meta)
  783. for col in columns:
  784. select_fields.append(len(select))
  785. select.append((col, None))
  786. klass_info['select_fields'] = select_fields
  787. next_klass_infos = self.get_related_selections(
  788. select, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted)
  789. get_related_klass_infos(klass_info, next_klass_infos)
  790. if restricted:
  791. related_fields = [
  792. (o.field, o.related_model)
  793. for o in opts.related_objects
  794. if o.field.unique and not o.many_to_many
  795. ]
  796. for f, model in related_fields:
  797. if not select_related_descend(f, restricted, requested,
  798. only_load.get(model), reverse=True):
  799. continue
  800. related_field_name = f.related_query_name()
  801. fields_found.add(related_field_name)
  802. join_info = self.query.setup_joins([related_field_name], opts, root_alias)
  803. alias = join_info.joins[-1]
  804. from_parent = issubclass(model, opts.model) and model is not opts.model
  805. klass_info = {
  806. 'model': model,
  807. 'field': f,
  808. 'reverse': True,
  809. 'local_setter': f.remote_field.set_cached_value,
  810. 'remote_setter': f.set_cached_value,
  811. 'from_parent': from_parent,
  812. }
  813. related_klass_infos.append(klass_info)
  814. select_fields = []
  815. columns = self.get_default_columns(
  816. start_alias=alias, opts=model._meta, from_parent=opts.model)
  817. for col in columns:
  818. select_fields.append(len(select))
  819. select.append((col, None))
  820. klass_info['select_fields'] = select_fields
  821. next = requested.get(f.related_query_name(), {})
  822. next_klass_infos = self.get_related_selections(
  823. select, model._meta, alias, cur_depth + 1,
  824. next, restricted)
  825. get_related_klass_infos(klass_info, next_klass_infos)
  826. def local_setter(obj, from_obj):
  827. # Set a reverse fk object when relation is non-empty.
  828. if from_obj:
  829. f.remote_field.set_cached_value(from_obj, obj)
  830. def remote_setter(name, obj, from_obj):
  831. setattr(from_obj, name, obj)
  832. for name in list(requested):
  833. # Filtered relations work only on the topmost level.
  834. if cur_depth > 1:
  835. break
  836. if name in self.query._filtered_relations:
  837. fields_found.add(name)
  838. f, _, join_opts, joins, _, _ = self.query.setup_joins([name], opts, root_alias)
  839. model = join_opts.model
  840. alias = joins[-1]
  841. from_parent = issubclass(model, opts.model) and model is not opts.model
  842. klass_info = {
  843. 'model': model,
  844. 'field': f,
  845. 'reverse': True,
  846. 'local_setter': local_setter,
  847. 'remote_setter': partial(remote_setter, name),
  848. 'from_parent': from_parent,
  849. }
  850. related_klass_infos.append(klass_info)
  851. select_fields = []
  852. columns = self.get_default_columns(
  853. start_alias=alias, opts=model._meta,
  854. from_parent=opts.model,
  855. )
  856. for col in columns:
  857. select_fields.append(len(select))
  858. select.append((col, None))
  859. klass_info['select_fields'] = select_fields
  860. next_requested = requested.get(name, {})
  861. next_klass_infos = self.get_related_selections(
  862. select, opts=model._meta, root_alias=alias,
  863. cur_depth=cur_depth + 1, requested=next_requested,
  864. restricted=restricted,
  865. )
  866. get_related_klass_infos(klass_info, next_klass_infos)
  867. fields_not_found = set(requested).difference(fields_found)
  868. if fields_not_found:
  869. invalid_fields = ("'%s'" % s for s in fields_not_found)
  870. raise FieldError(
  871. 'Invalid field name(s) given in select_related: %s. '
  872. 'Choices are: %s' % (
  873. ', '.join(invalid_fields),
  874. ', '.join(_get_field_choices()) or '(none)',
  875. )
  876. )
  877. return related_klass_infos
  878. def get_select_for_update_of_arguments(self):
  879. """
  880. Return a quoted list of arguments for the SELECT FOR UPDATE OF part of
  881. the query.
  882. """
  883. def _get_parent_klass_info(klass_info):
  884. return (
  885. {
  886. 'model': parent_model,
  887. 'field': parent_link,
  888. 'reverse': False,
  889. 'select_fields': [
  890. select_index
  891. for select_index in klass_info['select_fields']
  892. if self.select[select_index][0].target.model == parent_model
  893. ],
  894. }
  895. for parent_model, parent_link in klass_info['model']._meta.parents.items()
  896. )
  897. def _get_field_choices():
  898. """Yield all allowed field paths in breadth-first search order."""
  899. queue = collections.deque([(None, self.klass_info)])
  900. while queue:
  901. parent_path, klass_info = queue.popleft()
  902. if parent_path is None:
  903. path = []
  904. yield 'self'
  905. else:
  906. field = klass_info['field']
  907. if klass_info['reverse']:
  908. field = field.remote_field
  909. path = parent_path + [field.name]
  910. yield LOOKUP_SEP.join(path)
  911. queue.extend(
  912. (path, klass_info)
  913. for klass_info in _get_parent_klass_info(klass_info)
  914. )
  915. queue.extend(
  916. (path, klass_info)
  917. for klass_info in klass_info.get('related_klass_infos', [])
  918. )
  919. result = []
  920. invalid_names = []
  921. for name in self.query.select_for_update_of:
  922. klass_info = self.klass_info
  923. if name == 'self':
  924. # Find the first selected column from a base model. If it
  925. # doesn't exist, don't lock a base model.
  926. for select_index in klass_info['select_fields']:
  927. if self.select[select_index][0].target.model == klass_info['model']:
  928. col = self.select[select_index][0]
  929. break
  930. else:
  931. col = None
  932. else:
  933. for part in name.split(LOOKUP_SEP):
  934. klass_infos = (
  935. *klass_info.get('related_klass_infos', []),
  936. *_get_parent_klass_info(klass_info),
  937. )
  938. for related_klass_info in klass_infos:
  939. field = related_klass_info['field']
  940. if related_klass_info['reverse']:
  941. field = field.remote_field
  942. if field.name == part:
  943. klass_info = related_klass_info
  944. break
  945. else:
  946. klass_info = None
  947. break
  948. if klass_info is None:
  949. invalid_names.append(name)
  950. continue
  951. select_index = klass_info['select_fields'][0]
  952. col = self.select[select_index][0]
  953. if col is not None:
  954. if self.connection.features.select_for_update_of_column:
  955. result.append(self.compile(col)[0])
  956. else:
  957. result.append(self.quote_name_unless_alias(col.alias))
  958. if invalid_names:
  959. raise FieldError(
  960. 'Invalid field name(s) given in select_for_update(of=(...)): %s. '
  961. 'Only relational fields followed in the query are allowed. '
  962. 'Choices are: %s.' % (
  963. ', '.join(invalid_names),
  964. ', '.join(_get_field_choices()),
  965. )
  966. )
  967. return result
  968. def deferred_to_columns(self):
  969. """
  970. Convert the self.deferred_loading data structure to mapping of table
  971. names to sets of column names which are to be loaded. Return the
  972. dictionary.
  973. """
  974. columns = {}
  975. self.query.deferred_to_data(columns, self.query.get_loaded_field_names_cb)
  976. return columns
  977. def get_converters(self, expressions):
  978. converters = {}
  979. for i, expression in enumerate(expressions):
  980. if expression:
  981. backend_converters = self.connection.ops.get_db_converters(expression)
  982. field_converters = expression.get_db_converters(self.connection)
  983. if backend_converters or field_converters:
  984. converters[i] = (backend_converters + field_converters, expression)
  985. return converters
  986. def apply_converters(self, rows, converters):
  987. connection = self.connection
  988. converters = list(converters.items())
  989. for row in map(list, rows):
  990. for pos, (convs, expression) in converters:
  991. value = row[pos]
  992. for converter in convs:
  993. value = converter(value, expression, connection)
  994. row[pos] = value
  995. yield row
  996. def results_iter(self, results=None, tuple_expected=False, chunked_fetch=False,
  997. chunk_size=GET_ITERATOR_CHUNK_SIZE):
  998. """Return an iterator over the results from executing this query."""
  999. if results is None:
  1000. results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
  1001. fields = [s[0] for s in self.select[0:self.col_count]]
  1002. converters = self.get_converters(fields)
  1003. rows = chain.from_iterable(results)
  1004. if converters:
  1005. rows = self.apply_converters(rows, converters)
  1006. if tuple_expected:
  1007. rows = map(tuple, rows)
  1008. return rows
  1009. def has_results(self):
  1010. """
  1011. Backends (e.g. NoSQL) can override this in order to use optimized
  1012. versions of "query has any results."
  1013. """
  1014. # This is always executed on a query clone, so we can modify self.query
  1015. self.query.add_extra({'a': 1}, None, None, None, None, None)
  1016. self.query.set_extra_mask(['a'])
  1017. return bool(self.execute_sql(SINGLE))
  1018. def execute_sql(self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE):
  1019. """
  1020. Run the query against the database and return the result(s). The
  1021. return value is a single data item if result_type is SINGLE, or an
  1022. iterator over the results if the result_type is MULTI.
  1023. result_type is either MULTI (use fetchmany() to retrieve all rows),
  1024. SINGLE (only retrieve a single row), or None. In this last case, the
  1025. cursor is returned if any query is executed, since it's used by
  1026. subclasses such as InsertQuery). It's possible, however, that no query
  1027. is needed, as the filters describe an empty set. In that case, None is
  1028. returned, to avoid any unnecessary database interaction.
  1029. """
  1030. result_type = result_type or NO_RESULTS
  1031. try:
  1032. sql, params = self.as_sql()
  1033. if not sql:
  1034. raise EmptyResultSet
  1035. except EmptyResultSet:
  1036. if result_type == MULTI:
  1037. return iter([])
  1038. else:
  1039. return
  1040. if chunked_fetch:
  1041. cursor = self.connection.chunked_cursor()
  1042. else:
  1043. cursor = self.connection.cursor()
  1044. try:
  1045. cursor.execute(sql, params)
  1046. except Exception:
  1047. # Might fail for server-side cursors (e.g. connection closed)
  1048. cursor.close()
  1049. raise
  1050. if result_type == CURSOR:
  1051. # Give the caller the cursor to process and close.
  1052. return cursor
  1053. if result_type == SINGLE:
  1054. try:
  1055. val = cursor.fetchone()
  1056. if val:
  1057. return val[0:self.col_count]
  1058. return val
  1059. finally:
  1060. # done with the cursor
  1061. cursor.close()
  1062. if result_type == NO_RESULTS:
  1063. cursor.close()
  1064. return
  1065. result = cursor_iter(
  1066. cursor, self.connection.features.empty_fetchmany_value,
  1067. self.col_count if self.has_extra_select else None,
  1068. chunk_size,
  1069. )
  1070. if not chunked_fetch or not self.connection.features.can_use_chunked_reads:
  1071. try:
  1072. # If we are using non-chunked reads, we return the same data
  1073. # structure as normally, but ensure it is all read into memory
  1074. # before going any further. Use chunked_fetch if requested,
  1075. # unless the database doesn't support it.
  1076. return list(result)
  1077. finally:
  1078. # done with the cursor
  1079. cursor.close()
  1080. return result
  1081. def as_subquery_condition(self, alias, columns, compiler):
  1082. qn = compiler.quote_name_unless_alias
  1083. qn2 = self.connection.ops.quote_name
  1084. for index, select_col in enumerate(self.query.select):
  1085. lhs_sql, lhs_params = self.compile(select_col)
  1086. rhs = '%s.%s' % (qn(alias), qn2(columns[index]))
  1087. self.query.where.add(
  1088. RawSQL('%s = %s' % (lhs_sql, rhs), lhs_params), 'AND')
  1089. sql, params = self.as_sql()
  1090. return 'EXISTS (%s)' % sql, params
  1091. def explain_query(self):
  1092. result = list(self.execute_sql())
  1093. # Some backends return 1 item tuples with strings, and others return
  1094. # tuples with integers and strings. Flatten them out into strings.
  1095. for row in result[0]:
  1096. if not isinstance(row, str):
  1097. yield ' '.join(str(c) for c in row)
  1098. else:
  1099. yield row
  1100. class SQLInsertCompiler(SQLCompiler):
  1101. returning_fields = None
  1102. returning_params = tuple()
  1103. def field_as_sql(self, field, val):
  1104. """
  1105. Take a field and a value intended to be saved on that field, and
  1106. return placeholder SQL and accompanying params. Check for raw values,
  1107. expressions, and fields with get_placeholder() defined in that order.
  1108. When field is None, consider the value raw and use it as the
  1109. placeholder, with no corresponding parameters returned.
  1110. """
  1111. if field is None:
  1112. # A field value of None means the value is raw.
  1113. sql, params = val, []
  1114. elif hasattr(val, 'as_sql'):
  1115. # This is an expression, let's compile it.
  1116. sql, params = self.compile(val)
  1117. elif hasattr(field, 'get_placeholder'):
  1118. # Some fields (e.g. geo fields) need special munging before
  1119. # they can be inserted.
  1120. sql, params = field.get_placeholder(val, self, self.connection), [val]
  1121. else:
  1122. # Return the common case for the placeholder
  1123. sql, params = '%s', [val]
  1124. # The following hook is only used by Oracle Spatial, which sometimes
  1125. # needs to yield 'NULL' and [] as its placeholder and params instead
  1126. # of '%s' and [None]. The 'NULL' placeholder is produced earlier by
  1127. # OracleOperations.get_geom_placeholder(). The following line removes
  1128. # the corresponding None parameter. See ticket #10888.
  1129. params = self.connection.ops.modify_insert_params(sql, params)
  1130. return sql, params
  1131. def prepare_value(self, field, value):
  1132. """
  1133. Prepare a value to be used in a query by resolving it if it is an
  1134. expression and otherwise calling the field's get_db_prep_save().
  1135. """
  1136. if hasattr(value, 'resolve_expression'):
  1137. value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
  1138. # Don't allow values containing Col expressions. They refer to
  1139. # existing columns on a row, but in the case of insert the row
  1140. # doesn't exist yet.
  1141. if value.contains_column_references:
  1142. raise ValueError(
  1143. 'Failed to insert expression "%s" on %s. F() expressions '
  1144. 'can only be used to update, not to insert.' % (value, field)
  1145. )
  1146. if value.contains_aggregate:
  1147. raise FieldError(
  1148. 'Aggregate functions are not allowed in this query '
  1149. '(%s=%r).' % (field.name, value)
  1150. )
  1151. if value.contains_over_clause:
  1152. raise FieldError(
  1153. 'Window expressions are not allowed in this query (%s=%r).'
  1154. % (field.name, value)
  1155. )
  1156. else:
  1157. value = field.get_db_prep_save(value, connection=self.connection)
  1158. return value
  1159. def pre_save_val(self, field, obj):
  1160. """
  1161. Get the given field's value off the given obj. pre_save() is used for
  1162. things like auto_now on DateTimeField. Skip it if this is a raw query.
  1163. """
  1164. if self.query.raw:
  1165. return getattr(obj, field.attname)
  1166. return field.pre_save(obj, add=True)
  1167. def assemble_as_sql(self, fields, value_rows):
  1168. """
  1169. Take a sequence of N fields and a sequence of M rows of values, and
  1170. generate placeholder SQL and parameters for each field and value.
  1171. Return a pair containing:
  1172. * a sequence of M rows of N SQL placeholder strings, and
  1173. * a sequence of M rows of corresponding parameter values.
  1174. Each placeholder string may contain any number of '%s' interpolation
  1175. strings, and each parameter row will contain exactly as many params
  1176. as the total number of '%s's in the corresponding placeholder row.
  1177. """
  1178. if not value_rows:
  1179. return [], []
  1180. # list of (sql, [params]) tuples for each object to be saved
  1181. # Shape: [n_objs][n_fields][2]
  1182. rows_of_fields_as_sql = (
  1183. (self.field_as_sql(field, v) for field, v in zip(fields, row))
  1184. for row in value_rows
  1185. )
  1186. # tuple like ([sqls], [[params]s]) for each object to be saved
  1187. # Shape: [n_objs][2][n_fields]
  1188. sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql)
  1189. # Extract separate lists for placeholders and params.
  1190. # Each of these has shape [n_objs][n_fields]
  1191. placeholder_rows, param_rows = zip(*sql_and_param_pair_rows)
  1192. # Params for each field are still lists, and need to be flattened.
  1193. param_rows = [[p for ps in row for p in ps] for row in param_rows]
  1194. return placeholder_rows, param_rows
  1195. def as_sql(self):
  1196. # We don't need quote_name_unless_alias() here, since these are all
  1197. # going to be column names (so we can avoid the extra overhead).
  1198. qn = self.connection.ops.quote_name
  1199. opts = self.query.get_meta()
  1200. insert_statement = self.connection.ops.insert_statement(ignore_conflicts=self.query.ignore_conflicts)
  1201. result = ['%s %s' % (insert_statement, qn(opts.db_table))]
  1202. fields = self.query.fields or [opts.pk]
  1203. result.append('(%s)' % ', '.join(qn(f.column) for f in fields))
  1204. if self.query.fields:
  1205. value_rows = [
  1206. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  1207. for obj in self.query.objs
  1208. ]
  1209. else:
  1210. # An empty object.
  1211. value_rows = [[self.connection.ops.pk_default_value()] for _ in self.query.objs]
  1212. fields = [None]
  1213. # Currently the backends just accept values when generating bulk
  1214. # queries and generate their own placeholders. Doing that isn't
  1215. # necessary and it should be possible to use placeholders and
  1216. # expressions in bulk inserts too.
  1217. can_bulk = (not self.returning_fields and self.connection.features.has_bulk_insert)
  1218. placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)
  1219. ignore_conflicts_suffix_sql = self.connection.ops.ignore_conflicts_suffix_sql(
  1220. ignore_conflicts=self.query.ignore_conflicts
  1221. )
  1222. if self.returning_fields and self.connection.features.can_return_columns_from_insert:
  1223. if self.connection.features.can_return_rows_from_bulk_insert:
  1224. result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
  1225. params = param_rows
  1226. else:
  1227. result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
  1228. params = [param_rows[0]]
  1229. if ignore_conflicts_suffix_sql:
  1230. result.append(ignore_conflicts_suffix_sql)
  1231. # Skip empty r_sql to allow subclasses to customize behavior for
  1232. # 3rd party backends. Refs #19096.
  1233. r_sql, self.returning_params = self.connection.ops.return_insert_columns(self.returning_fields)
  1234. if r_sql:
  1235. result.append(r_sql)
  1236. params += [self.returning_params]
  1237. return [(" ".join(result), tuple(chain.from_iterable(params)))]
  1238. if can_bulk:
  1239. result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
  1240. if ignore_conflicts_suffix_sql:
  1241. result.append(ignore_conflicts_suffix_sql)
  1242. return [(" ".join(result), tuple(p for ps in param_rows for p in ps))]
  1243. else:
  1244. if ignore_conflicts_suffix_sql:
  1245. result.append(ignore_conflicts_suffix_sql)
  1246. return [
  1247. (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
  1248. for p, vals in zip(placeholder_rows, param_rows)
  1249. ]
  1250. def execute_sql(self, returning_fields=None):
  1251. assert not (
  1252. returning_fields and len(self.query.objs) != 1 and
  1253. not self.connection.features.can_return_rows_from_bulk_insert
  1254. )
  1255. self.returning_fields = returning_fields
  1256. with self.connection.cursor() as cursor:
  1257. for sql, params in self.as_sql():
  1258. cursor.execute(sql, params)
  1259. if not self.returning_fields:
  1260. return []
  1261. if self.connection.features.can_return_rows_from_bulk_insert and len(self.query.objs) > 1:
  1262. return self.connection.ops.fetch_returned_insert_rows(cursor)
  1263. if self.connection.features.can_return_columns_from_insert:
  1264. assert len(self.query.objs) == 1
  1265. return self.connection.ops.fetch_returned_insert_columns(cursor, self.returning_params)
  1266. return [self.connection.ops.last_insert_id(
  1267. cursor, self.query.get_meta().db_table, self.query.get_meta().pk.column
  1268. )]
  1269. class SQLDeleteCompiler(SQLCompiler):
  1270. @cached_property
  1271. def single_alias(self):
  1272. return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1
  1273. def _as_sql(self, query):
  1274. result = [
  1275. 'DELETE FROM %s' % self.quote_name_unless_alias(query.base_table)
  1276. ]
  1277. where, params = self.compile(query.where)
  1278. if where:
  1279. result.append('WHERE %s' % where)
  1280. return ' '.join(result), tuple(params)
  1281. def as_sql(self):
  1282. """
  1283. Create the SQL for this query. Return the SQL string and list of
  1284. parameters.
  1285. """
  1286. if self.single_alias:
  1287. return self._as_sql(self.query)
  1288. innerq = self.query.clone()
  1289. innerq.__class__ = Query
  1290. innerq.clear_select_clause()
  1291. pk = self.query.model._meta.pk
  1292. innerq.select = [
  1293. pk.get_col(self.query.get_initial_alias())
  1294. ]
  1295. outerq = Query(self.query.model)
  1296. outerq.where = self.query.where_class()
  1297. outerq.add_q(Q(pk__in=innerq))
  1298. return self._as_sql(outerq)
  1299. class SQLUpdateCompiler(SQLCompiler):
  1300. def as_sql(self):
  1301. """
  1302. Create the SQL for this query. Return the SQL string and list of
  1303. parameters.
  1304. """
  1305. self.pre_sql_setup()
  1306. if not self.query.values:
  1307. return '', ()
  1308. qn = self.quote_name_unless_alias
  1309. values, update_params = [], []
  1310. for field, model, val in self.query.values:
  1311. if hasattr(val, 'resolve_expression'):
  1312. val = val.resolve_expression(self.query, allow_joins=False, for_save=True)
  1313. if val.contains_aggregate:
  1314. raise FieldError(
  1315. 'Aggregate functions are not allowed in this query '
  1316. '(%s=%r).' % (field.name, val)
  1317. )
  1318. if val.contains_over_clause:
  1319. raise FieldError(
  1320. 'Window expressions are not allowed in this query '
  1321. '(%s=%r).' % (field.name, val)
  1322. )
  1323. elif hasattr(val, 'prepare_database_save'):
  1324. if field.remote_field:
  1325. val = field.get_db_prep_save(
  1326. val.prepare_database_save(field),
  1327. connection=self.connection,
  1328. )
  1329. else:
  1330. raise TypeError(
  1331. "Tried to update field %s with a model instance, %r. "
  1332. "Use a value compatible with %s."
  1333. % (field, val, field.__class__.__name__)
  1334. )
  1335. else:
  1336. val = field.get_db_prep_save(val, connection=self.connection)
  1337. # Getting the placeholder for the field.
  1338. if hasattr(field, 'get_placeholder'):
  1339. placeholder = field.get_placeholder(val, self, self.connection)
  1340. else:
  1341. placeholder = '%s'
  1342. name = field.column
  1343. if hasattr(val, 'as_sql'):
  1344. sql, params = self.compile(val)
  1345. values.append('%s = %s' % (qn(name), placeholder % sql))
  1346. update_params.extend(params)
  1347. elif val is not None:
  1348. values.append('%s = %s' % (qn(name), placeholder))
  1349. update_params.append(val)
  1350. else:
  1351. values.append('%s = NULL' % qn(name))
  1352. table = self.query.base_table
  1353. result = [
  1354. 'UPDATE %s SET' % qn(table),
  1355. ', '.join(values),
  1356. ]
  1357. where, params = self.compile(self.query.where)
  1358. if where:
  1359. result.append('WHERE %s' % where)
  1360. return ' '.join(result), tuple(update_params + params)
  1361. def execute_sql(self, result_type):
  1362. """
  1363. Execute the specified update. Return the number of rows affected by
  1364. the primary update query. The "primary update query" is the first
  1365. non-empty query that is executed. Row counts for any subsequent,
  1366. related queries are not available.
  1367. """
  1368. cursor = super().execute_sql(result_type)
  1369. try:
  1370. rows = cursor.rowcount if cursor else 0
  1371. is_empty = cursor is None
  1372. finally:
  1373. if cursor:
  1374. cursor.close()
  1375. for query in self.query.get_related_updates():
  1376. aux_rows = query.get_compiler(self.using).execute_sql(result_type)
  1377. if is_empty and aux_rows:
  1378. rows = aux_rows
  1379. is_empty = False
  1380. return rows
  1381. def pre_sql_setup(self):
  1382. """
  1383. If the update depends on results from other tables, munge the "where"
  1384. conditions to match the format required for (portable) SQL updates.
  1385. If multiple updates are required, pull out the id values to update at
  1386. this point so that they don't change as a result of the progressive
  1387. updates.
  1388. """
  1389. refcounts_before = self.query.alias_refcount.copy()
  1390. # Ensure base table is in the query
  1391. self.query.get_initial_alias()
  1392. count = self.query.count_active_tables()
  1393. if not self.query.related_updates and count == 1:
  1394. return
  1395. query = self.query.chain(klass=Query)
  1396. query.select_related = False
  1397. query.clear_ordering(True)
  1398. query.extra = {}
  1399. query.select = []
  1400. query.add_fields([query.get_meta().pk.name])
  1401. super().pre_sql_setup()
  1402. must_pre_select = count > 1 and not self.connection.features.update_can_self_select
  1403. # Now we adjust the current query: reset the where clause and get rid
  1404. # of all the tables we don't need (since they're in the sub-select).
  1405. self.query.where = self.query.where_class()
  1406. if self.query.related_updates or must_pre_select:
  1407. # Either we're using the idents in multiple update queries (so
  1408. # don't want them to change), or the db backend doesn't support
  1409. # selecting from the updating table (e.g. MySQL).
  1410. idents = []
  1411. for rows in query.get_compiler(self.using).execute_sql(MULTI):
  1412. idents.extend(r[0] for r in rows)
  1413. self.query.add_filter(('pk__in', idents))
  1414. self.query.related_ids = idents
  1415. else:
  1416. # The fast path. Filters and updates in one query.
  1417. self.query.add_filter(('pk__in', query))
  1418. self.query.reset_refcounts(refcounts_before)
  1419. class SQLAggregateCompiler(SQLCompiler):
  1420. def as_sql(self):
  1421. """
  1422. Create the SQL for this query. Return the SQL string and list of
  1423. parameters.
  1424. """
  1425. sql, params = [], []
  1426. for annotation in self.query.annotation_select.values():
  1427. ann_sql, ann_params = self.compile(annotation)
  1428. ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params)
  1429. sql.append(ann_sql)
  1430. params.extend(ann_params)
  1431. self.col_count = len(self.query.annotation_select)
  1432. sql = ', '.join(sql)
  1433. params = tuple(params)
  1434. sql = 'SELECT %s FROM (%s) subquery' % (sql, self.query.subquery)
  1435. params = params + self.query.sub_params
  1436. return sql, params
  1437. def cursor_iter(cursor, sentinel, col_count, itersize):
  1438. """
  1439. Yield blocks of rows from a cursor and ensure the cursor is closed when
  1440. done.
  1441. """
  1442. try:
  1443. for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
  1444. yield rows if col_count is None else [r[:col_count] for r in rows]
  1445. finally:
  1446. cursor.close()