PageRenderTime 99ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/django/branches/attic/queryset-refactor/django/db/models/sql/subqueries.py

https://bitbucket.org/mirror/django/
Python | 367 lines | 332 code | 8 blank | 27 comment | 8 complexity | c2f92d4edc8190e096c4c90cacffcbff MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. Query subclasses which provide extra functionality beyond simple data retrieval.
  3. """
  4. from django.contrib.contenttypes import generic
  5. from django.core.exceptions import FieldError
  6. from django.db.models.sql.constants import *
  7. from django.db.models.sql.datastructures import RawValue, Date
  8. from django.db.models.sql.query import Query
  9. from django.db.models.sql.where import AND
  10. __all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'DateQuery',
  11. 'CountQuery']
  12. class DeleteQuery(Query):
  13. """
  14. Delete queries are done through this class, since they are more constrained
  15. than general queries.
  16. """
  17. def as_sql(self):
  18. """
  19. Creates the SQL for this query. Returns the SQL string and list of
  20. parameters.
  21. """
  22. assert len(self.tables) == 1, \
  23. "Can only delete from one table at a time."
  24. result = ['DELETE FROM %s' % self.quote_name_unless_alias(self.tables[0])]
  25. where, params = self.where.as_sql()
  26. result.append('WHERE %s' % where)
  27. return ' '.join(result), tuple(params)
  28. def do_query(self, table, where):
  29. self.tables = [table]
  30. self.where = where
  31. self.execute_sql(None)
  32. def delete_batch_related(self, pk_list):
  33. """
  34. Set up and execute delete queries for all the objects related to the
  35. primary key values in pk_list. To delete the objects themselves, use
  36. the delete_batch() method.
  37. More than one physical query may be executed if there are a
  38. lot of values in pk_list.
  39. """
  40. cls = self.model
  41. for related in cls._meta.get_all_related_many_to_many_objects():
  42. if not isinstance(related.field, generic.GenericRelation):
  43. for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
  44. where = self.where_class()
  45. where.add((None, related.field.m2m_reverse_name(),
  46. related.field, 'in',
  47. pk_list[offset : offset+GET_ITERATOR_CHUNK_SIZE]),
  48. AND)
  49. self.do_query(related.field.m2m_db_table(), where)
  50. for f in cls._meta.many_to_many:
  51. w1 = self.where_class()
  52. if isinstance(f, generic.GenericRelation):
  53. from django.contrib.contenttypes.models import ContentType
  54. field = f.rel.to._meta.get_field(f.content_type_field_name)
  55. w1.add((None, field.column, field, 'exact',
  56. ContentType.objects.get_for_model(cls).id), AND)
  57. for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
  58. where = self.where_class()
  59. where.add((None, f.m2m_column_name(), f, 'in',
  60. pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]),
  61. AND)
  62. if w1:
  63. where.add(w1, AND)
  64. self.do_query(f.m2m_db_table(), where)
  65. def delete_batch(self, pk_list):
  66. """
  67. Set up and execute delete queries for all the objects in pk_list. This
  68. should be called after delete_batch_related(), if necessary.
  69. More than one physical query may be executed if there are a
  70. lot of values in pk_list.
  71. """
  72. for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
  73. where = self.where_class()
  74. field = self.model._meta.pk
  75. where.add((None, field.column, field, 'in',
  76. pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]), AND)
  77. self.do_query(self.model._meta.db_table, where)
  78. class UpdateQuery(Query):
  79. """
  80. Represents an "update" SQL query.
  81. """
  82. def __init__(self, *args, **kwargs):
  83. super(UpdateQuery, self).__init__(*args, **kwargs)
  84. self._setup_query()
  85. def _setup_query(self):
  86. """
  87. Runs on initialisation and after cloning. Any attributes that would
  88. normally be set in __init__ should go in here, instead, so that they
  89. are also set up after a clone() call.
  90. """
  91. self.values = []
  92. self.related_ids = None
  93. if not hasattr(self, 'related_updates'):
  94. self.related_updates = {}
  95. def clone(self, klass=None, **kwargs):
  96. return super(UpdateQuery, self).clone(klass,
  97. related_updates=self.related_updates.copy, **kwargs)
  98. def execute_sql(self, result_type=None):
  99. super(UpdateQuery, self).execute_sql(result_type)
  100. for query in self.get_related_updates():
  101. query.execute_sql(result_type)
  102. def as_sql(self):
  103. """
  104. Creates the SQL for this query. Returns the SQL string and list of
  105. parameters.
  106. """
  107. self.pre_sql_setup()
  108. if not self.values:
  109. return '', ()
  110. table = self.tables[0]
  111. qn = self.quote_name_unless_alias
  112. result = ['UPDATE %s' % qn(table)]
  113. result.append('SET')
  114. values, update_params = [], []
  115. for name, val, placeholder in self.values:
  116. if val is not None:
  117. values.append('%s = %s' % (qn(name), placeholder))
  118. update_params.append(val)
  119. else:
  120. values.append('%s = NULL' % qn(name))
  121. result.append(', '.join(values))
  122. where, params = self.where.as_sql()
  123. if where:
  124. result.append('WHERE %s' % where)
  125. return ' '.join(result), tuple(update_params + params)
  126. def pre_sql_setup(self):
  127. """
  128. If the update depends on results from other tables, we need to do some
  129. munging of the "where" conditions to match the format required for
  130. (portable) SQL updates. That is done here.
  131. Further, if we are going to be running multiple updates, we pull out
  132. the id values to update at this point so that they don't change as a
  133. result of the progressive updates.
  134. """
  135. self.select_related = False
  136. self.clear_ordering(True)
  137. super(UpdateQuery, self).pre_sql_setup()
  138. count = self.count_active_tables()
  139. if not self.related_updates and count == 1:
  140. return
  141. # We need to use a sub-select in the where clause to filter on things
  142. # from other tables.
  143. query = self.clone(klass=Query)
  144. query.bump_prefix()
  145. query.select = []
  146. query.extra_select = {}
  147. query.add_fields([query.model._meta.pk.name])
  148. # Now we adjust the current query: reset the where clause and get rid
  149. # of all the tables we don't need (since they're in the sub-select).
  150. self.where = self.where_class()
  151. if self.related_updates:
  152. idents = []
  153. for rows in query.execute_sql(MULTI):
  154. idents.extend([r[0] for r in rows])
  155. self.add_filter(('pk__in', idents))
  156. self.related_ids = idents
  157. else:
  158. self.add_filter(('pk__in', query))
  159. for alias in self.tables[1:]:
  160. self.alias_refcount[alias] = 0
  161. def clear_related(self, related_field, pk_list):
  162. """
  163. Set up and execute an update query that clears related entries for the
  164. keys in pk_list.
  165. This is used by the QuerySet.delete_objects() method.
  166. """
  167. for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
  168. self.where = self.where_class()
  169. f = self.model._meta.pk
  170. self.where.add((None, f.column, f, 'in',
  171. pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]),
  172. AND)
  173. self.values = [(related_field.column, None, '%s')]
  174. self.execute_sql(None)
  175. def add_update_values(self, values):
  176. """
  177. Convert a dictionary of field name to value mappings into an update
  178. query. This is the entry point for the public update() method on
  179. querysets.
  180. """
  181. values_seq = []
  182. for name, val in values.iteritems():
  183. field, model, direct, m2m = self.model._meta.get_field_by_name(name)
  184. if not direct or m2m:
  185. raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field)
  186. values_seq.append((field, model, val))
  187. return self.add_update_fields(values_seq)
  188. def add_update_fields(self, values_seq):
  189. """
  190. Turn a sequence of (field, model, value) triples into an update query.
  191. Used by add_update_values() as well as the "fast" update path when
  192. saving models.
  193. """
  194. from django.db.models.base import Model
  195. for field, model, val in values_seq:
  196. # FIXME: Some sort of db_prep_* is probably more appropriate here.
  197. if field.rel and isinstance(val, Model):
  198. val = val.pk
  199. # Getting the placeholder for the field.
  200. if hasattr(field, 'get_placeholder'):
  201. placeholder = field.get_placeholder(val)
  202. else:
  203. placeholder = '%s'
  204. if model:
  205. self.add_related_update(model, field.column, val, placeholder)
  206. else:
  207. self.values.append((field.column, val, placeholder))
  208. def add_related_update(self, model, column, value, placeholder):
  209. """
  210. Adds (name, value) to an update query for an ancestor model.
  211. Updates are coalesced so that we only run one update query per ancestor.
  212. """
  213. try:
  214. self.related_updates[model].append((column, value, placeholder))
  215. except KeyError:
  216. self.related_updates[model] = [(column, value, placeholder)]
  217. def get_related_updates(self):
  218. """
  219. Returns a list of query objects: one for each update required to an
  220. ancestor model. Each query will have the same filtering conditions as
  221. the current query but will only update a single table.
  222. """
  223. if not self.related_updates:
  224. return []
  225. result = []
  226. for model, values in self.related_updates.iteritems():
  227. query = UpdateQuery(model, self.connection)
  228. query.values = values
  229. if self.related_ids:
  230. query.add_filter(('pk__in', self.related_ids))
  231. result.append(query)
  232. return result
  233. class InsertQuery(Query):
  234. def __init__(self, *args, **kwargs):
  235. super(InsertQuery, self).__init__(*args, **kwargs)
  236. self.columns = []
  237. self.values = []
  238. self.params = ()
  239. def clone(self, klass=None, **kwargs):
  240. extras = {'columns': self.columns[:], 'values': self.values[:],
  241. 'params': self.params}
  242. return super(InsertQuery, self).clone(klass, extras)
  243. def as_sql(self):
  244. # We don't need quote_name_unless_alias() here, since these are all
  245. # going to be column names (so we can avoid the extra overhead).
  246. qn = self.connection.ops.quote_name
  247. result = ['INSERT INTO %s' % qn(self.model._meta.db_table)]
  248. result.append('(%s)' % ', '.join([qn(c) for c in self.columns]))
  249. result.append('VALUES (%s)' % ', '.join(self.values))
  250. return ' '.join(result), self.params
  251. def execute_sql(self, return_id=False):
  252. cursor = super(InsertQuery, self).execute_sql(None)
  253. if return_id:
  254. return self.connection.ops.last_insert_id(cursor,
  255. self.model._meta.db_table, self.model._meta.pk.column)
  256. def insert_values(self, insert_values, raw_values=False):
  257. """
  258. Set up the insert query from the 'insert_values' dictionary. The
  259. dictionary gives the model field names and their target values.
  260. If 'raw_values' is True, the values in the 'insert_values' dictionary
  261. are inserted directly into the query, rather than passed as SQL
  262. parameters. This provides a way to insert NULL and DEFAULT keywords
  263. into the query, for example.
  264. """
  265. placeholders, values = [], []
  266. for field, val in insert_values:
  267. if hasattr(field, 'get_placeholder'):
  268. # Some fields (e.g. geo fields) need special munging before
  269. # they can be inserted.
  270. placeholders.append(field.get_placeholder(val))
  271. else:
  272. placeholders.append('%s')
  273. self.columns.append(field.column)
  274. values.append(val)
  275. if raw_values:
  276. self.values.extend(values)
  277. else:
  278. self.params += tuple(values)
  279. self.values.extend(placeholders)
  280. class DateQuery(Query):
  281. """
  282. A DateQuery is a normal query, except that it specifically selects a single
  283. date field. This requires some special handling when converting the results
  284. back to Python objects, so we put it in a separate class.
  285. """
  286. def results_iter(self):
  287. """
  288. Returns an iterator over the results from executing this query.
  289. """
  290. resolve_columns = hasattr(self, 'resolve_columns')
  291. if resolve_columns:
  292. from django.db.models.fields import DateTimeField
  293. fields = [DateTimeField()]
  294. else:
  295. from django.db.backends.util import typecast_timestamp
  296. needs_string_cast = self.connection.features.needs_datetime_string_cast
  297. offset = len(self.extra_select)
  298. for rows in self.execute_sql(MULTI):
  299. for row in rows:
  300. date = row[offset]
  301. if resolve_columns:
  302. date = self.resolve_columns([date], fields)[0]
  303. elif needs_string_cast:
  304. date = typecast_timestamp(str(date))
  305. yield date
  306. def add_date_select(self, column, lookup_type, order='ASC'):
  307. """
  308. Converts the query into a date extraction query.
  309. """
  310. alias = self.join((None, self.model._meta.db_table, None, None))
  311. select = Date((alias, column), lookup_type,
  312. self.connection.ops.date_trunc_sql)
  313. self.select = [select]
  314. self.select_fields = [None]
  315. self.distinct = True
  316. self.order_by = order == 'ASC' and [1] or [-1]
  317. class CountQuery(Query):
  318. """
  319. A CountQuery knows how to take a normal query which would select over
  320. multiple distinct columns and turn it into SQL that can be used on a
  321. variety of backends (it requires a select in the FROM clause).
  322. """
  323. def get_from_clause(self):
  324. result, params = self._query.as_sql()
  325. return ['(%s) A1' % result], params
  326. def get_ordering(self):
  327. return ()