compiler.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. import datetime
  2. from django.conf import settings
  3. from django.core.exceptions import FieldError
  4. from django.db.backends.utils import truncate_name
  5. from django.db.models.constants import LOOKUP_SEP
  6. from django.db.models.expressions import ExpressionNode
  7. from django.db.models.query_utils import select_related_descend, QueryWrapper
  8. from django.db.models.sql.constants import (CURSOR, SINGLE, MULTI, NO_RESULTS,
  9. ORDER_DIR, GET_ITERATOR_CHUNK_SIZE, SelectInfo)
  10. from django.db.models.sql.datastructures import EmptyResultSet
  11. from django.db.models.sql.expressions import SQLEvaluator
  12. from django.db.models.sql.query import get_order_dir, Query
  13. from django.db.transaction import TransactionManagementError
  14. from django.db.utils import DatabaseError
  15. from django.utils import six
  16. from django.utils.six.moves import zip
  17. from django.utils import timezone
  18. class SQLCompiler(object):
  19. def __init__(self, query, connection, using):
  20. self.query = query
  21. self.connection = connection
  22. self.using = using
  23. self.quote_cache = {'*': '*'}
  24. # When ordering a queryset with distinct on a column not part of the
  25. # select set, the ordering column needs to be added to the select
  26. # clause. This information is needed both in SQL construction and
  27. # masking away the ordering selects from the returned row.
  28. self.ordering_aliases = []
  29. self.ordering_params = []
  30. def pre_sql_setup(self):
  31. """
  32. Does any necessary class setup immediately prior to producing SQL. This
  33. is for things that can't necessarily be done in __init__ because we
  34. might not have all the pieces in place at that time.
  35. # TODO: after the query has been executed, the altered state should be
  36. # cleaned. We are not using a clone() of the query here.
  37. """
  38. if not self.query.tables:
  39. self.query.join((None, self.query.get_meta().db_table, None))
  40. if (not self.query.select and self.query.default_cols and not
  41. self.query.included_inherited_models):
  42. self.query.setup_inherited_models()
  43. if self.query.select_related and not self.query.related_select_cols:
  44. self.fill_related_selections()
  45. def __call__(self, name):
  46. """
  47. A wrapper around connection.ops.quote_name that doesn't quote aliases
  48. for table names. This avoids problems with some SQL dialects that treat
  49. quoted strings specially (e.g. PostgreSQL).
  50. """
  51. if name in self.quote_cache:
  52. return self.quote_cache[name]
  53. if ((name in self.query.alias_map and name not in self.query.table_map) or
  54. name in self.query.extra_select):
  55. self.quote_cache[name] = name
  56. return name
  57. r = self.connection.ops.quote_name(name)
  58. self.quote_cache[name] = r
  59. return r
  60. def quote_name_unless_alias(self, name):
  61. """
  62. A wrapper around connection.ops.quote_name that doesn't quote aliases
  63. for table names. This avoids problems with some SQL dialects that treat
  64. quoted strings specially (e.g. PostgreSQL).
  65. """
  66. return self(name)
  67. def compile(self, node):
  68. vendor_impl = getattr(
  69. node, 'as_' + self.connection.vendor, None)
  70. if vendor_impl:
  71. return vendor_impl(self, self.connection)
  72. else:
  73. return node.as_sql(self, self.connection)
  74. def as_sql(self, with_limits=True, with_col_aliases=False):
  75. """
  76. Creates the SQL for this query. Returns the SQL string and list of
  77. parameters.
  78. If 'with_limits' is False, any limit/offset information is not included
  79. in the query.
  80. """
  81. if with_limits and self.query.low_mark == self.query.high_mark:
  82. return '', ()
  83. self.pre_sql_setup()
  84. # After executing the query, we must get rid of any joins the query
  85. # setup created. So, take note of alias counts before the query ran.
  86. # However we do not want to get rid of stuff done in pre_sql_setup(),
  87. # as the pre_sql_setup will modify query state in a way that forbids
  88. # another run of it.
  89. self.refcounts_before = self.query.alias_refcount.copy()
  90. out_cols, s_params = self.get_columns(with_col_aliases)
  91. ordering, o_params, ordering_group_by = self.get_ordering()
  92. distinct_fields = self.get_distinct()
  93. # This must come after 'select', 'ordering' and 'distinct' -- see
  94. # docstring of get_from_clause() for details.
  95. from_, f_params = self.get_from_clause()
  96. where, w_params = self.compile(self.query.where)
  97. having, h_params = self.compile(self.query.having)
  98. having_group_by = self.query.having.get_group_by_cols()
  99. params = []
  100. for val in six.itervalues(self.query.extra_select):
  101. params.extend(val[1])
  102. result = ['SELECT']
  103. if self.query.distinct:
  104. result.append(self.connection.ops.distinct_sql(distinct_fields))
  105. result.append(', '.join(out_cols + self.ordering_aliases))
  106. params.extend(s_params)
  107. params.extend(self.ordering_params)
  108. result.append('FROM')
  109. result.extend(from_)
  110. params.extend(f_params)
  111. if where:
  112. result.append('WHERE %s' % where)
  113. params.extend(w_params)
  114. grouping, gb_params = self.get_grouping(having_group_by, ordering_group_by)
  115. if grouping:
  116. if distinct_fields:
  117. raise NotImplementedError(
  118. "annotate() + distinct(fields) not implemented.")
  119. if not ordering:
  120. ordering = self.connection.ops.force_no_ordering()
  121. result.append('GROUP BY %s' % ', '.join(grouping))
  122. params.extend(gb_params)
  123. if having:
  124. result.append('HAVING %s' % having)
  125. params.extend(h_params)
  126. if ordering:
  127. result.append('ORDER BY %s' % ', '.join(ordering))
  128. params.extend(o_params)
  129. if with_limits:
  130. if self.query.high_mark is not None:
  131. result.append('LIMIT %d' % (self.query.high_mark - self.query.low_mark))
  132. if self.query.low_mark:
  133. if self.query.high_mark is None:
  134. val = self.connection.ops.no_limit_value()
  135. if val:
  136. result.append('LIMIT %d' % val)
  137. result.append('OFFSET %d' % self.query.low_mark)
  138. if self.query.select_for_update and self.connection.features.has_select_for_update:
  139. if self.connection.get_autocommit():
  140. raise TransactionManagementError("select_for_update cannot be used outside of a transaction.")
  141. # If we've been asked for a NOWAIT query but the backend does not support it,
  142. # raise a DatabaseError otherwise we could get an unexpected deadlock.
  143. nowait = self.query.select_for_update_nowait
  144. if nowait and not self.connection.features.has_select_for_update_nowait:
  145. raise DatabaseError('NOWAIT is not supported on this database backend.')
  146. result.append(self.connection.ops.for_update_sql(nowait=nowait))
  147. # Finally do cleanup - get rid of the joins we created above.
  148. self.query.reset_refcounts(self.refcounts_before)
  149. return ' '.join(result), tuple(params)
  150. def as_nested_sql(self):
  151. """
  152. Perform the same functionality as the as_sql() method, returning an
  153. SQL string and parameters. However, the alias prefixes are bumped
  154. beforehand (in a copy -- the current query isn't changed), and any
  155. ordering is removed if the query is unsliced.
  156. Used when nesting this query inside another.
  157. """
  158. obj = self.query.clone()
  159. if obj.low_mark == 0 and obj.high_mark is None and not self.query.distinct_fields:
  160. # If there is no slicing in use, then we can safely drop all ordering
  161. obj.clear_ordering(True)
  162. return obj.get_compiler(connection=self.connection).as_sql()
  163. def get_columns(self, with_aliases=False):
  164. """
  165. Returns the list of columns to use in the select statement, as well as
  166. a list any extra parameters that need to be included. If no columns
  167. have been specified, returns all columns relating to fields in the
  168. model.
  169. If 'with_aliases' is true, any column names that are duplicated
  170. (without the table names) are given unique aliases. This is needed in
  171. some cases to avoid ambiguity with nested queries.
  172. """
  173. qn = self
  174. qn2 = self.connection.ops.quote_name
  175. result = ['(%s) AS %s' % (col[0], qn2(alias)) for alias, col in six.iteritems(self.query.extra_select)]
  176. params = []
  177. aliases = set(self.query.extra_select.keys())
  178. if with_aliases:
  179. col_aliases = aliases.copy()
  180. else:
  181. col_aliases = set()
  182. if self.query.select:
  183. only_load = self.deferred_to_columns()
  184. for col, _ in self.query.select:
  185. if isinstance(col, (list, tuple)):
  186. alias, column = col
  187. table = self.query.alias_map[alias].table_name
  188. if table in only_load and column not in only_load[table]:
  189. continue
  190. r = '%s.%s' % (qn(alias), qn(column))
  191. if with_aliases:
  192. if col[1] in col_aliases:
  193. c_alias = 'Col%d' % len(col_aliases)
  194. result.append('%s AS %s' % (r, c_alias))
  195. aliases.add(c_alias)
  196. col_aliases.add(c_alias)
  197. else:
  198. result.append('%s AS %s' % (r, qn2(col[1])))
  199. aliases.add(r)
  200. col_aliases.add(col[1])
  201. else:
  202. result.append(r)
  203. aliases.add(r)
  204. col_aliases.add(col[1])
  205. else:
  206. col_sql, col_params = self.compile(col)
  207. result.append(col_sql)
  208. params.extend(col_params)
  209. if hasattr(col, 'alias'):
  210. aliases.add(col.alias)
  211. col_aliases.add(col.alias)
  212. elif self.query.default_cols:
  213. cols, new_aliases = self.get_default_columns(with_aliases,
  214. col_aliases)
  215. result.extend(cols)
  216. aliases.update(new_aliases)
  217. max_name_length = self.connection.ops.max_name_length()
  218. for alias, aggregate in self.query.aggregate_select.items():
  219. agg_sql, agg_params = self.compile(aggregate)
  220. if alias is None:
  221. result.append(agg_sql)
  222. else:
  223. result.append('%s AS %s' % (agg_sql, qn(truncate_name(alias, max_name_length))))
  224. params.extend(agg_params)
  225. for (table, col), _ in self.query.related_select_cols:
  226. r = '%s.%s' % (qn(table), qn(col))
  227. if with_aliases and col in col_aliases:
  228. c_alias = 'Col%d' % len(col_aliases)
  229. result.append('%s AS %s' % (r, c_alias))
  230. aliases.add(c_alias)
  231. col_aliases.add(c_alias)
  232. else:
  233. result.append(r)
  234. aliases.add(r)
  235. col_aliases.add(col)
  236. self._select_aliases = aliases
  237. return result, params
  238. def get_default_columns(self, with_aliases=False, col_aliases=None,
  239. start_alias=None, opts=None, as_pairs=False, from_parent=None):
  240. """
  241. Computes the default columns for selecting every field in the base
  242. model. Will sometimes be called to pull in related models (e.g. via
  243. select_related), in which case "opts" and "start_alias" will be given
  244. to provide a starting point for the traversal.
  245. Returns a list of strings, quoted appropriately for use in SQL
  246. directly, as well as a set of aliases used in the select statement (if
  247. 'as_pairs' is True, returns a list of (alias, col_name) pairs instead
  248. of strings as the first component and None as the second component).
  249. """
  250. result = []
  251. if opts is None:
  252. opts = self.query.get_meta()
  253. qn = self
  254. qn2 = self.connection.ops.quote_name
  255. aliases = set()
  256. only_load = self.deferred_to_columns()
  257. if not start_alias:
  258. start_alias = self.query.get_initial_alias()
  259. # The 'seen_models' is used to optimize checking the needed parent
  260. # alias for a given field. This also includes None -> start_alias to
  261. # be used by local fields.
  262. seen_models = {None: start_alias}
  263. for field, model in opts.get_concrete_fields_with_model():
  264. if from_parent and model is not None and issubclass(from_parent, model):
  265. # Avoid loading data for already loaded parents.
  266. continue
  267. alias = self.query.join_parent_model(opts, model, start_alias,
  268. seen_models)
  269. column = field.column
  270. for seen_model, seen_alias in seen_models.items():
  271. if seen_model and seen_alias == alias:
  272. ancestor_link = seen_model._meta.get_ancestor_link(model)
  273. if ancestor_link:
  274. column = ancestor_link.column
  275. break
  276. table = self.query.alias_map[alias].table_name
  277. if table in only_load and column not in only_load[table]:
  278. continue
  279. if as_pairs:
  280. result.append((alias, field))
  281. aliases.add(alias)
  282. continue
  283. if with_aliases and column in col_aliases:
  284. c_alias = 'Col%d' % len(col_aliases)
  285. result.append('%s.%s AS %s' % (qn(alias),
  286. qn2(column), c_alias))
  287. col_aliases.add(c_alias)
  288. aliases.add(c_alias)
  289. else:
  290. r = '%s.%s' % (qn(alias), qn2(column))
  291. result.append(r)
  292. aliases.add(r)
  293. if with_aliases:
  294. col_aliases.add(column)
  295. return result, aliases
  296. def get_distinct(self):
  297. """
  298. Returns a quoted list of fields to use in DISTINCT ON part of the query.
  299. Note that this method can alter the tables in the query, and thus it
  300. must be called before get_from_clause().
  301. """
  302. qn = self
  303. qn2 = self.connection.ops.quote_name
  304. result = []
  305. opts = self.query.get_meta()
  306. for name in self.query.distinct_fields:
  307. parts = name.split(LOOKUP_SEP)
  308. _, targets, alias, joins, path, _ = self._setup_joins(parts, opts, None)
  309. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  310. for target in targets:
  311. result.append("%s.%s" % (qn(alias), qn2(target.column)))
  312. return result
  313. def get_ordering(self):
  314. """
  315. Returns a tuple containing a list representing the SQL elements in the
  316. "order by" clause, and the list of SQL elements that need to be added
  317. to the GROUP BY clause as a result of the ordering.
  318. Also sets the ordering_aliases attribute on this instance to a list of
  319. extra aliases needed in the select.
  320. Determining the ordering SQL can change the tables we need to include,
  321. so this should be run *before* get_from_clause().
  322. """
  323. if self.query.extra_order_by:
  324. ordering = self.query.extra_order_by
  325. elif not self.query.default_ordering:
  326. ordering = self.query.order_by
  327. else:
  328. ordering = (self.query.order_by
  329. or self.query.get_meta().ordering
  330. or [])
  331. qn = self
  332. qn2 = self.connection.ops.quote_name
  333. distinct = self.query.distinct
  334. select_aliases = self._select_aliases
  335. result = []
  336. group_by = []
  337. ordering_aliases = []
  338. if self.query.standard_ordering:
  339. asc, desc = ORDER_DIR['ASC']
  340. else:
  341. asc, desc = ORDER_DIR['DESC']
  342. # It's possible, due to model inheritance, that normal usage might try
  343. # to include the same field more than once in the ordering. We track
  344. # the table/column pairs we use and discard any after the first use.
  345. processed_pairs = set()
  346. params = []
  347. ordering_params = []
  348. # For plain DISTINCT queries any ORDER BY clause must appear
  349. # in SELECT clause.
  350. # http://www.postgresql.org/message-id/27009.1171559417@sss.pgh.pa.us
  351. must_append_to_select = distinct and not self.query.distinct_fields
  352. for pos, field in enumerate(ordering):
  353. if field == '?':
  354. result.append(self.connection.ops.random_function_sql())
  355. continue
  356. if isinstance(field, int):
  357. if field < 0:
  358. order = desc
  359. field = -field
  360. else:
  361. order = asc
  362. result.append('%s %s' % (field, order))
  363. group_by.append((str(field), []))
  364. continue
  365. col, order = get_order_dir(field, asc)
  366. if col in self.query.aggregate_select:
  367. result.append('%s %s' % (qn(col), order))
  368. continue
  369. if '.' in field:
  370. # This came in through an extra(order_by=...) addition. Pass it
  371. # on verbatim.
  372. table, col = col.split('.', 1)
  373. if (table, col) not in processed_pairs:
  374. elt = '%s.%s' % (qn(table), col)
  375. processed_pairs.add((table, col))
  376. if not must_append_to_select or elt in select_aliases:
  377. result.append('%s %s' % (elt, order))
  378. group_by.append((elt, []))
  379. elif not self.query._extra or get_order_dir(field)[0] not in self.query._extra:
  380. # 'col' is of the form 'field' or 'field1__field2' or
  381. # '-field1__field2__field', etc.
  382. for table, cols, order in self.find_ordering_name(field,
  383. self.query.get_meta(), default_order=asc):
  384. for col in cols:
  385. if (table, col) not in processed_pairs:
  386. elt = '%s.%s' % (qn(table), qn2(col))
  387. processed_pairs.add((table, col))
  388. if must_append_to_select and elt not in select_aliases:
  389. ordering_aliases.append(elt)
  390. result.append('%s %s' % (elt, order))
  391. group_by.append((elt, []))
  392. else:
  393. elt = qn2(col)
  394. if col not in self.query.extra_select:
  395. if must_append_to_select:
  396. sql = "(%s) AS %s" % (self.query.extra[col][0], elt)
  397. ordering_aliases.append(sql)
  398. ordering_params.extend(self.query.extra[col][1])
  399. result.append('%s %s' % (elt, order))
  400. else:
  401. result.append("(%s) %s" % (self.query.extra[col][0], order))
  402. params.extend(self.query.extra[col][1])
  403. else:
  404. result.append('%s %s' % (elt, order))
  405. group_by.append(self.query.extra[col])
  406. self.ordering_aliases = ordering_aliases
  407. self.ordering_params = ordering_params
  408. return result, params, group_by
  409. def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
  410. already_seen=None):
  411. """
  412. Returns the table alias (the name might be ambiguous, the alias will
  413. not be) and column name for ordering by the given 'name' parameter.
  414. The 'name' is of the form 'field1__field2__...__fieldN'.
  415. """
  416. name, order = get_order_dir(name, default_order)
  417. pieces = name.split(LOOKUP_SEP)
  418. field, targets, alias, joins, path, opts = self._setup_joins(pieces, opts, alias)
  419. # If we get to this point and the field is a relation to another model,
  420. # append the default ordering for that model unless the attribute name
  421. # of the field is specified.
  422. if field.rel and path and opts.ordering and name != field.attname:
  423. # Firstly, avoid infinite loops.
  424. if not already_seen:
  425. already_seen = set()
  426. join_tuple = tuple(self.query.alias_map[j].table_name for j in joins)
  427. if join_tuple in already_seen:
  428. raise FieldError('Infinite loop caused by ordering.')
  429. already_seen.add(join_tuple)
  430. results = []
  431. for item in opts.ordering:
  432. results.extend(self.find_ordering_name(item, opts, alias,
  433. order, already_seen))
  434. return results
  435. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  436. return [(alias, [t.column for t in targets], order)]
  437. def _setup_joins(self, pieces, opts, alias):
  438. """
  439. A helper method for get_ordering and get_distinct.
  440. Note that get_ordering and get_distinct must produce same target
  441. columns on same input, as the prefixes of get_ordering and get_distinct
  442. must match. Executing SQL where this is not true is an error.
  443. """
  444. if not alias:
  445. alias = self.query.get_initial_alias()
  446. field, targets, opts, joins, path = self.query.setup_joins(
  447. pieces, opts, alias)
  448. alias = joins[-1]
  449. return field, targets, alias, joins, path, opts
  450. def get_from_clause(self):
  451. """
  452. Returns a list of strings that are joined together to go after the
  453. "FROM" part of the query, as well as a list any extra parameters that
  454. need to be included. Sub-classes, can override this to create a
  455. from-clause via a "select".
  456. This should only be called after any SQL construction methods that
  457. might change the tables we need. This means the select columns,
  458. ordering and distinct must be done first.
  459. """
  460. result = []
  461. qn = self
  462. qn2 = self.connection.ops.quote_name
  463. first = True
  464. from_params = []
  465. for alias in self.query.tables:
  466. if not self.query.alias_refcount[alias]:
  467. continue
  468. try:
  469. name, alias, join_type, lhs, join_cols, _, join_field = self.query.alias_map[alias]
  470. except KeyError:
  471. # Extra tables can end up in self.tables, but not in the
  472. # alias_map if they aren't in a join. That's OK. We skip them.
  473. continue
  474. alias_str = '' if alias == name else (' %s' % alias)
  475. if join_type and not first:
  476. extra_cond = join_field.get_extra_restriction(
  477. self.query.where_class, alias, lhs)
  478. if extra_cond:
  479. extra_sql, extra_params = self.compile(extra_cond)
  480. extra_sql = 'AND (%s)' % extra_sql
  481. from_params.extend(extra_params)
  482. else:
  483. extra_sql = ""
  484. result.append('%s %s%s ON ('
  485. % (join_type, qn(name), alias_str))
  486. for index, (lhs_col, rhs_col) in enumerate(join_cols):
  487. if index != 0:
  488. result.append(' AND ')
  489. result.append('%s.%s = %s.%s' %
  490. (qn(lhs), qn2(lhs_col), qn(alias), qn2(rhs_col)))
  491. result.append('%s)' % extra_sql)
  492. else:
  493. connector = '' if first else ', '
  494. result.append('%s%s%s' % (connector, qn(name), alias_str))
  495. first = False
  496. for t in self.query.extra_tables:
  497. alias, unused = self.query.table_alias(t)
  498. # Only add the alias if it's not already present (the table_alias()
  499. # calls increments the refcount, so an alias refcount of one means
  500. # this is the only reference.
  501. if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1:
  502. connector = '' if first else ', '
  503. result.append('%s%s' % (connector, qn(alias)))
  504. first = False
  505. return result, from_params
  506. def get_grouping(self, having_group_by, ordering_group_by):
  507. """
  508. Returns a tuple representing the SQL elements in the "group by" clause.
  509. """
  510. qn = self
  511. result, params = [], []
  512. if self.query.group_by is not None:
  513. select_cols = self.query.select + self.query.related_select_cols
  514. # Just the column, not the fields.
  515. select_cols = [s[0] for s in select_cols]
  516. if (len(self.query.get_meta().concrete_fields) == len(self.query.select)
  517. and self.connection.features.allows_group_by_pk):
  518. self.query.group_by = [
  519. (self.query.get_meta().db_table, self.query.get_meta().pk.column)
  520. ]
  521. select_cols = []
  522. seen = set()
  523. cols = self.query.group_by + having_group_by + select_cols
  524. for col in cols:
  525. col_params = ()
  526. if isinstance(col, (list, tuple)):
  527. sql = '%s.%s' % (qn(col[0]), qn(col[1]))
  528. elif hasattr(col, 'as_sql'):
  529. self.compile(col)
  530. else:
  531. sql = '(%s)' % str(col)
  532. if sql not in seen:
  533. result.append(sql)
  534. params.extend(col_params)
  535. seen.add(sql)
  536. # Still, we need to add all stuff in ordering (except if the backend can
  537. # group by just by PK).
  538. if ordering_group_by and not self.connection.features.allows_group_by_pk:
  539. for order, order_params in ordering_group_by:
  540. # Even if we have seen the same SQL string, it might have
  541. # different params, so, we add same SQL in "has params" case.
  542. if order not in seen or order_params:
  543. result.append(order)
  544. params.extend(order_params)
  545. seen.add(order)
  546. # Unconditionally add the extra_select items.
  547. for extra_select, extra_params in self.query.extra_select.values():
  548. sql = '(%s)' % str(extra_select)
  549. result.append(sql)
  550. params.extend(extra_params)
  551. return result, params
  552. def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1,
  553. requested=None, restricted=None):
  554. """
  555. Fill in the information needed for a select_related query. The current
  556. depth is measured as the number of connections away from the root model
  557. (for example, cur_depth=1 means we are looking at models with direct
  558. connections to the root model).
  559. """
  560. if not restricted and self.query.max_depth and cur_depth > self.query.max_depth:
  561. # We've recursed far enough; bail out.
  562. return
  563. if not opts:
  564. opts = self.query.get_meta()
  565. root_alias = self.query.get_initial_alias()
  566. self.query.related_select_cols = []
  567. only_load = self.query.get_loaded_field_names()
  568. # Setup for the case when only particular related fields should be
  569. # included in the related selection.
  570. if requested is None:
  571. if isinstance(self.query.select_related, dict):
  572. requested = self.query.select_related
  573. restricted = True
  574. else:
  575. restricted = False
  576. for f, model in opts.get_fields_with_model():
  577. # The get_fields_with_model() returns None for fields that live
  578. # in the field's local model. So, for those fields we want to use
  579. # the f.model - that is the field's local model.
  580. field_model = model or f.model
  581. if not select_related_descend(f, restricted, requested,
  582. only_load.get(field_model)):
  583. continue
  584. _, _, _, joins, _ = self.query.setup_joins(
  585. [f.name], opts, root_alias)
  586. alias = joins[-1]
  587. columns, _ = self.get_default_columns(start_alias=alias,
  588. opts=f.rel.to._meta, as_pairs=True)
  589. self.query.related_select_cols.extend(
  590. SelectInfo((col[0], col[1].column), col[1]) for col in columns)
  591. if restricted:
  592. next = requested.get(f.name, {})
  593. else:
  594. next = False
  595. self.fill_related_selections(f.rel.to._meta, alias, cur_depth + 1,
  596. next, restricted)
  597. if restricted:
  598. related_fields = [
  599. (o.field, o.model)
  600. for o in opts.get_all_related_objects()
  601. if o.field.unique
  602. ]
  603. for f, model in related_fields:
  604. if not select_related_descend(f, restricted, requested,
  605. only_load.get(model), reverse=True):
  606. continue
  607. _, _, _, joins, _ = self.query.setup_joins(
  608. [f.related_query_name()], opts, root_alias)
  609. alias = joins[-1]
  610. from_parent = (opts.model if issubclass(model, opts.model)
  611. else None)
  612. columns, _ = self.get_default_columns(start_alias=alias,
  613. opts=model._meta, as_pairs=True, from_parent=from_parent)
  614. self.query.related_select_cols.extend(
  615. SelectInfo((col[0], col[1].column), col[1]) for col in columns)
  616. next = requested.get(f.related_query_name(), {})
  617. self.fill_related_selections(model._meta, alias, cur_depth + 1,
  618. next, restricted)
  619. def deferred_to_columns(self):
  620. """
  621. Converts the self.deferred_loading data structure to mapping of table
  622. names to sets of column names which are to be loaded. Returns the
  623. dictionary.
  624. """
  625. columns = {}
  626. self.query.deferred_to_data(columns, self.query.deferred_to_columns_cb)
  627. return columns
  628. def results_iter(self):
  629. """
  630. Returns an iterator over the results from executing this query.
  631. """
  632. resolve_columns = hasattr(self, 'resolve_columns')
  633. fields = None
  634. has_aggregate_select = bool(self.query.aggregate_select)
  635. for rows in self.execute_sql(MULTI):
  636. for row in rows:
  637. if has_aggregate_select:
  638. loaded_fields = self.query.get_loaded_field_names().get(self.query.model, set()) or self.query.select
  639. aggregate_start = len(self.query.extra_select) + len(loaded_fields)
  640. aggregate_end = aggregate_start + len(self.query.aggregate_select)
  641. if resolve_columns:
  642. if fields is None:
  643. # We only set this up here because
  644. # related_select_cols isn't populated until
  645. # execute_sql() has been called.
  646. # We also include types of fields of related models that
  647. # will be included via select_related() for the benefit
  648. # of MySQL/MySQLdb when boolean fields are involved
  649. # (#15040).
  650. # This code duplicates the logic for the order of fields
  651. # found in get_columns(). It would be nice to clean this up.
  652. if self.query.select:
  653. fields = [f.field for f in self.query.select]
  654. elif self.query.default_cols:
  655. fields = self.query.get_meta().concrete_fields
  656. else:
  657. fields = []
  658. fields = fields + [f.field for f in self.query.related_select_cols]
  659. # If the field was deferred, exclude it from being passed
  660. # into `resolve_columns` because it wasn't selected.
  661. only_load = self.deferred_to_columns()
  662. if only_load:
  663. fields = [f for f in fields if f.model._meta.db_table not in only_load or
  664. f.column in only_load[f.model._meta.db_table]]
  665. if has_aggregate_select:
  666. # pad None in to fields for aggregates
  667. fields = fields[:aggregate_start] + [
  668. None for x in range(0, aggregate_end - aggregate_start)
  669. ] + fields[aggregate_start:]
  670. row = self.resolve_columns(row, fields)
  671. if has_aggregate_select:
  672. row = tuple(row[:aggregate_start]) + tuple(
  673. self.query.resolve_aggregate(value, aggregate, self.connection)
  674. for (alias, aggregate), value
  675. in zip(self.query.aggregate_select.items(), row[aggregate_start:aggregate_end])
  676. ) + tuple(row[aggregate_end:])
  677. yield row
  678. def has_results(self):
  679. """
  680. Backends (e.g. NoSQL) can override this in order to use optimized
  681. versions of "query has any results."
  682. """
  683. # This is always executed on a query clone, so we can modify self.query
  684. self.query.add_extra({'a': 1}, None, None, None, None, None)
  685. self.query.set_extra_mask(['a'])
  686. return bool(self.execute_sql(SINGLE))
  687. def execute_sql(self, result_type=MULTI):
  688. """
  689. Run the query against the database and returns the result(s). The
  690. return value is a single data item if result_type is SINGLE, or an
  691. iterator over the results if the result_type is MULTI.
  692. result_type is either MULTI (use fetchmany() to retrieve all rows),
  693. SINGLE (only retrieve a single row), or None. In this last case, the
  694. cursor is returned if any query is executed, since it's used by
  695. subclasses such as InsertQuery). It's possible, however, that no query
  696. is needed, as the filters describe an empty set. In that case, None is
  697. returned, to avoid any unnecessary database interaction.
  698. """
  699. if not result_type:
  700. result_type = NO_RESULTS
  701. try:
  702. sql, params = self.as_sql()
  703. if not sql:
  704. raise EmptyResultSet
  705. except EmptyResultSet:
  706. if result_type == MULTI:
  707. return iter([])
  708. else:
  709. return
  710. cursor = self.connection.cursor()
  711. try:
  712. cursor.execute(sql, params)
  713. except Exception:
  714. cursor.close()
  715. raise
  716. if result_type == CURSOR:
  717. # Caller didn't specify a result_type, so just give them back the
  718. # cursor to process (and close).
  719. return cursor
  720. if result_type == SINGLE:
  721. try:
  722. if self.ordering_aliases:
  723. return cursor.fetchone()[:-len(self.ordering_aliases)]
  724. return cursor.fetchone()
  725. finally:
  726. # done with the cursor
  727. cursor.close()
  728. if result_type == NO_RESULTS:
  729. cursor.close()
  730. return
  731. # The MULTI case.
  732. if self.ordering_aliases:
  733. result = order_modified_iter(cursor, len(self.ordering_aliases),
  734. self.connection.features.empty_fetchmany_value)
  735. else:
  736. result = cursor_iter(cursor,
  737. self.connection.features.empty_fetchmany_value)
  738. if not self.connection.features.can_use_chunked_reads:
  739. try:
  740. # If we are using non-chunked reads, we return the same data
  741. # structure as normally, but ensure it is all read into memory
  742. # before going any further.
  743. return list(result)
  744. finally:
  745. # done with the cursor
  746. cursor.close()
  747. return result
  748. def as_subquery_condition(self, alias, columns, qn):
  749. inner_qn = self
  750. qn2 = self.connection.ops.quote_name
  751. if len(columns) == 1:
  752. sql, params = self.as_sql()
  753. return '%s.%s IN (%s)' % (qn(alias), qn2(columns[0]), sql), params
  754. for index, select_col in enumerate(self.query.select):
  755. lhs = '%s.%s' % (inner_qn(select_col.col[0]), qn2(select_col.col[1]))
  756. rhs = '%s.%s' % (qn(alias), qn2(columns[index]))
  757. self.query.where.add(
  758. QueryWrapper('%s = %s' % (lhs, rhs), []), 'AND')
  759. sql, params = self.as_sql()
  760. return 'EXISTS (%s)' % sql, params
  761. class SQLInsertCompiler(SQLCompiler):
  762. def __init__(self, *args, **kwargs):
  763. self.return_id = False
  764. super(SQLInsertCompiler, self).__init__(*args, **kwargs)
  765. def placeholder(self, field, val):
  766. if field is None:
  767. # A field value of None means the value is raw.
  768. return val
  769. elif hasattr(field, 'get_placeholder'):
  770. # Some fields (e.g. geo fields) need special munging before
  771. # they can be inserted.
  772. return field.get_placeholder(val, self.connection)
  773. else:
  774. # Return the common case for the placeholder
  775. return '%s'
  776. def as_sql(self):
  777. # We don't need quote_name_unless_alias() here, since these are all
  778. # going to be column names (so we can avoid the extra overhead).
  779. qn = self.connection.ops.quote_name
  780. opts = self.query.get_meta()
  781. result = ['INSERT INTO %s' % qn(opts.db_table)]
  782. has_fields = bool(self.query.fields)
  783. fields = self.query.fields if has_fields else [opts.pk]
  784. result.append('(%s)' % ', '.join(qn(f.column) for f in fields))
  785. if has_fields:
  786. params = values = [
  787. [
  788. f.get_db_prep_save(getattr(obj, f.attname) if self.query.raw else f.pre_save(obj, True), connection=self.connection)
  789. for f in fields
  790. ]
  791. for obj in self.query.objs
  792. ]
  793. else:
  794. values = [[self.connection.ops.pk_default_value()] for obj in self.query.objs]
  795. params = [[]]
  796. fields = [None]
  797. can_bulk = (not any(hasattr(field, "get_placeholder") for field in fields) and
  798. not self.return_id and self.connection.features.has_bulk_insert)
  799. if can_bulk:
  800. placeholders = [["%s"] * len(fields)]
  801. else:
  802. placeholders = [
  803. [self.placeholder(field, v) for field, v in zip(fields, val)]
  804. for val in values
  805. ]
  806. # Oracle Spatial needs to remove some values due to #10888
  807. params = self.connection.ops.modify_insert_params(placeholders, params)
  808. if self.return_id and self.connection.features.can_return_id_from_insert:
  809. params = params[0]
  810. col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column))
  811. result.append("VALUES (%s)" % ", ".join(placeholders[0]))
  812. r_fmt, r_params = self.connection.ops.return_insert_id()
  813. # Skip empty r_fmt to allow subclasses to customize behavior for
  814. # 3rd party backends. Refs #19096.
  815. if r_fmt:
  816. result.append(r_fmt % col)
  817. params += r_params
  818. return [(" ".join(result), tuple(params))]
  819. if can_bulk:
  820. result.append(self.connection.ops.bulk_insert_sql(fields, len(values)))
  821. return [(" ".join(result), tuple(v for val in values for v in val))]
  822. else:
  823. return [
  824. (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
  825. for p, vals in zip(placeholders, params)
  826. ]
  827. def execute_sql(self, return_id=False):
  828. assert not (return_id and len(self.query.objs) != 1)
  829. self.return_id = return_id
  830. with self.connection.cursor() as cursor:
  831. for sql, params in self.as_sql():
  832. cursor.execute(sql, params)
  833. if not (return_id and cursor):
  834. return
  835. if self.connection.features.can_return_id_from_insert:
  836. return self.connection.ops.fetch_returned_insert_id(cursor)
  837. return self.connection.ops.last_insert_id(cursor,
  838. self.query.get_meta().db_table, self.query.get_meta().pk.column)
  839. class SQLDeleteCompiler(SQLCompiler):
  840. def as_sql(self):
  841. """
  842. Creates the SQL for this query. Returns the SQL string and list of
  843. parameters.
  844. """
  845. assert len(self.query.tables) == 1, \
  846. "Can only delete from one table at a time."
  847. qn = self
  848. result = ['DELETE FROM %s' % qn(self.query.tables[0])]
  849. where, params = self.compile(self.query.where)
  850. if where:
  851. result.append('WHERE %s' % where)
  852. return ' '.join(result), tuple(params)
  853. class SQLUpdateCompiler(SQLCompiler):
  854. def as_sql(self):
  855. """
  856. Creates the SQL for this query. Returns the SQL string and list of
  857. parameters.
  858. """
  859. self.pre_sql_setup()
  860. if not self.query.values:
  861. return '', ()
  862. table = self.query.tables[0]
  863. qn = self
  864. result = ['UPDATE %s' % qn(table)]
  865. result.append('SET')
  866. values, update_params = [], []
  867. for field, model, val in self.query.values:
  868. if hasattr(val, 'prepare_database_save'):
  869. if field.rel or isinstance(val, ExpressionNode):
  870. val = val.prepare_database_save(field)
  871. else:
  872. raise TypeError("Database is trying to update a relational field "
  873. "of type %s with a value of type %s. Make sure "
  874. "you are setting the correct relations" %
  875. (field.__class__.__name__, val.__class__.__name__))
  876. else:
  877. val = field.get_db_prep_save(val, connection=self.connection)
  878. # Getting the placeholder for the field.
  879. if hasattr(field, 'get_placeholder'):
  880. placeholder = field.get_placeholder(val, self.connection)
  881. else:
  882. placeholder = '%s'
  883. if hasattr(val, 'evaluate'):
  884. val = SQLEvaluator(val, self.query, allow_joins=False)
  885. name = field.column
  886. if hasattr(val, 'as_sql'):
  887. sql, params = self.compile(val)
  888. values.append('%s = %s' % (qn(name), sql))
  889. update_params.extend(params)
  890. elif val is not None:
  891. values.append('%s = %s' % (qn(name), placeholder))
  892. update_params.append(val)
  893. else:
  894. values.append('%s = NULL' % qn(name))
  895. if not values:
  896. return '', ()
  897. result.append(', '.join(values))
  898. where, params = self.compile(self.query.where)
  899. if where:
  900. result.append('WHERE %s' % where)
  901. return ' '.join(result), tuple(update_params + params)
  902. def execute_sql(self, result_type):
  903. """
  904. Execute the specified update. Returns the number of rows affected by
  905. the primary update query. The "primary update query" is the first
  906. non-empty query that is executed. Row counts for any subsequent,
  907. related queries are not available.
  908. """
  909. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  910. try:
  911. rows = cursor.rowcount if cursor else 0
  912. is_empty = cursor is None
  913. finally:
  914. if cursor:
  915. cursor.close()
  916. for query in self.query.get_related_updates():
  917. aux_rows = query.get_compiler(self.using).execute_sql(result_type)
  918. if is_empty and aux_rows:
  919. rows = aux_rows
  920. is_empty = False
  921. return rows
  922. def pre_sql_setup(self):
  923. """
  924. If the update depends on results from other tables, we need to do some
  925. munging of the "where" conditions to match the format required for
  926. (portable) SQL updates. That is done here.
  927. Further, if we are going to be running multiple updates, we pull out
  928. the id values to update at this point so that they don't change as a
  929. result of the progressive updates.
  930. """
  931. self.query.select_related = False
  932. self.query.clear_ordering(True)
  933. super(SQLUpdateCompiler, self).pre_sql_setup()
  934. count = self.query.count_active_tables()
  935. if not self.query.related_updates and count == 1:
  936. return
  937. # We need to use a sub-select in the where clause to filter on things
  938. # from other tables.
  939. query = self.query.clone(klass=Query)
  940. query._extra = {}
  941. query.select = []
  942. query.add_fields([query.get_meta().pk.name])
  943. # Recheck the count - it is possible that fiddling with the select
  944. # fields above removes tables from the query. Refs #18304.
  945. count = query.count_active_tables()
  946. if not self.query.related_updates and count == 1:
  947. return
  948. must_pre_select = count > 1 and not self.connection.features.update_can_self_select
  949. # Now we adjust the current query: reset the where clause and get rid
  950. # of all the tables we don't need (since they're in the sub-select).
  951. self.query.where = self.query.where_class()
  952. if self.query.related_updates or must_pre_select:
  953. # Either we're using the idents in multiple update queries (so
  954. # don't want them to change), or the db backend doesn't support
  955. # selecting from the updating table (e.g. MySQL).
  956. idents = []
  957. for rows in query.get_compiler(self.using).execute_sql(MULTI):
  958. idents.extend(r[0] for r in rows)
  959. self.query.add_filter(('pk__in', idents))
  960. self.query.related_ids = idents
  961. else:
  962. # The fast path. Filters and updates in one query.
  963. self.query.add_filter(('pk__in', query))
  964. for alias in self.query.tables[1:]:
  965. self.query.alias_refcount[alias] = 0
  966. class SQLAggregateCompiler(SQLCompiler):
  967. def as_sql(self, qn=None):
  968. """
  969. Creates the SQL for this query. Returns the SQL string and list of
  970. parameters.
  971. """
  972. if qn is None:
  973. qn = self
  974. sql, params = [], []
  975. for aggregate in self.query.aggregate_select.values():
  976. agg_sql, agg_params = self.compile(aggregate)
  977. sql.append(agg_sql)
  978. params.extend(agg_params)
  979. sql = ', '.join(sql)
  980. params = tuple(params)
  981. sql = 'SELECT %s FROM (%s) subquery' % (sql, self.query.subquery)
  982. params = params + self.query.sub_params
  983. return sql, params
  984. class SQLDateCompiler(SQLCompiler):
  985. def results_iter(self):
  986. """
  987. Returns an iterator over the results from executing this query.
  988. """
  989. resolve_columns = hasattr(self, 'resolve_columns')
  990. if resolve_columns:
  991. from django.db.models.fields import DateField
  992. fields = [DateField()]
  993. else:
  994. from django.db.backends.utils import typecast_date
  995. needs_string_cast = self.connection.features.needs_datetime_string_cast
  996. offset = len(self.query.extra_select)
  997. for rows in self.execute_sql(MULTI):
  998. for row in rows:
  999. date = row[offset]
  1000. if resolve_columns:
  1001. date = self.resolve_columns(row, fields)[offset]
  1002. elif needs_string_cast:
  1003. date = typecast_date(str(date))
  1004. if isinstance(date, datetime.datetime):
  1005. date = date.date()
  1006. yield date
  1007. class SQLDateTimeCompiler(SQLCompiler):
  1008. def results_iter(self):
  1009. """
  1010. Returns an iterator over the results from executing this query.
  1011. """
  1012. resolve_columns = hasattr(self, 'resolve_columns')
  1013. if resolve_columns:
  1014. from django.db.models.fields import DateTimeField
  1015. fields = [DateTimeField()]
  1016. else:
  1017. from django.db.backends.utils import typecast_timestamp
  1018. needs_string_cast = self.connection.features.needs_datetime_string_cast
  1019. offset = len(self.query.extra_select)
  1020. for rows in self.execute_sql(MULTI):
  1021. for row in rows:
  1022. datetime = row[offset]
  1023. if resolve_columns:
  1024. datetime = self.resolve_columns(row, fields)[offset]
  1025. elif needs_string_cast:
  1026. datetime = typecast_timestamp(str(datetime))
  1027. # Datetimes are artificially returned in UTC on databases that
  1028. # don't support time zone. Restore the zone used in the query.
  1029. if settings.USE_TZ:
  1030. if datetime is None:
  1031. raise ValueError("Database returned an invalid value "
  1032. "in QuerySet.datetimes(). Are time zone "
  1033. "definitions for your database and pytz installed?")
  1034. datetime = datetime.replace(tzinfo=None)
  1035. datetime = timezone.make_aware(datetime, self.query.tzinfo)
  1036. yield datetime
  1037. def cursor_iter(cursor, sentinel):
  1038. """
  1039. Yields blocks of rows from a cursor and ensures the cursor is closed when
  1040. done.
  1041. """
  1042. try:
  1043. for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
  1044. sentinel):
  1045. yield rows
  1046. finally:
  1047. cursor.close()
  1048. def order_modified_iter(cursor, trim, sentinel):
  1049. """
  1050. Yields blocks of rows from a cursor. We use this iterator in the special
  1051. case when extra output columns have been added to support ordering
  1052. requirements. We must trim those extra columns before anything else can use
  1053. the results, since they're only needed to make the SQL valid.
  1054. """
  1055. try:
  1056. for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)),
  1057. sentinel):
  1058. yield [r[:-trim] for r in rows]
  1059. finally:
  1060. cursor.close()