Source

django-nonrel / django / db / models / sql / subqueries.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
"""
Query subclasses which provide extra functionality beyond simple data retrieval.
"""

from django.core.exceptions import FieldError
from django.db import connections
from django.db import router
from django.db import DEFAULT_DB_ALIAS
from django.db.models.fields import DateField, FieldDoesNotExist
from django.db.models.sql.constants import *
from django.db.models.sql.datastructures import Date
from django.db.models.sql.expressions import SQLEvaluator
from django.db.models.sql.query import Query
from django.db.models.sql.where import AND, Constraint

__all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'DateQuery',
        'AggregateQuery']

class DeleteQuery(Query):
    """
    Delete queries are done through this class, since they are more constrained
    than general queries.
    """

    compiler = 'SQLDeleteCompiler'

    def do_query(self, table, where, using):
        self.tables = [table]
        self.where = where
        self.get_compiler(using).execute_sql(None)

    def delete_batch(self, pk_list, using, field=None):
        """
        Set up and execute delete queries for all the objects in pk_list.

        More than one physical query may be executed if there are a
        lot of values in pk_list.
        """
        if not field:
            field = self.model._meta.pk
        for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
            where = self.where_class()
            where.add((Constraint(None, field.column, field), 'in',
                    pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]), AND)
            self.do_query(self.model._meta.db_table, where, using=using)

class UpdateQuery(Query):
    """
    Represents an "update" SQL query.
    """

    compiler = 'SQLUpdateCompiler'

    def __init__(self, *args, **kwargs):
        super(UpdateQuery, self).__init__(*args, **kwargs)
        self._setup_query()

    def _setup_query(self):
        """
        Runs on initialization and after cloning. Any attributes that would
        normally be set in __init__ should go in here, instead, so that they
        are also set up after a clone() call.
        """
        self.values = []
        self.related_ids = None
        if not hasattr(self, 'related_updates'):
            self.related_updates = {}

    def clone(self, klass=None, **kwargs):
        return super(UpdateQuery, self).clone(klass,
                related_updates=self.related_updates.copy(), **kwargs)


    def update_batch(self, pk_list, values, using):
        pk_field = self.model._meta.pk
        self.add_update_values(values)
        for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
            self.where = self.where_class()
            self.where.add((Constraint(None, pk_field.column, pk_field), 'in',
                    pk_list[offset : offset + GET_ITERATOR_CHUNK_SIZE]),
                    AND)
            self.get_compiler(using).execute_sql(None)

    def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in values.iteritems():
            field, model, direct, m2m = self.model._meta.get_field_by_name(name)
            if not direct or m2m:
                raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field)
            if model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq)

    def add_update_fields(self, values_seq):
        """
        Turn a sequence of (field, model, value) triples into an update query.
        Used by add_update_values() as well as the "fast" update path when
        saving models.
        """
        self.values.extend(values_seq)

    def add_related_update(self, model, field, value):
        """
        Adds (name, value) to an update query for an ancestor model.

        Updates are coalesced so that we only run one update query per ancestor.
        """
        try:
            self.related_updates[model].append((field, None, value))
        except KeyError:
            self.related_updates[model] = [(field, None, value)]

    def get_related_updates(self):
        """
        Returns a list of query objects: one for each update required to an
        ancestor model. Each query will have the same filtering conditions as
        the current query but will only update a single table.
        """
        if not self.related_updates:
            return []
        result = []
        for model, values in self.related_updates.iteritems():
            query = UpdateQuery(model)
            query.values = values
            if self.related_ids is not None:
                query.add_filter(('pk__in', self.related_ids))
            result.append(query)
        return result

class InsertQuery(Query):
    compiler = 'SQLInsertCompiler'

    def __init__(self, *args, **kwargs):
        super(InsertQuery, self).__init__(*args, **kwargs)
        self.columns = []
        self.values = []
        self.params = ()

    def clone(self, klass=None, **kwargs):
        extras = {
            'columns': self.columns[:],
            'values': self.values[:],
            'params': self.params
        }
        extras.update(kwargs)
        return super(InsertQuery, self).clone(klass, **extras)

    def insert_values(self, insert_values, raw_values=False):
        """
        Set up the insert query from the 'insert_values' dictionary. The
        dictionary gives the model field names and their target values.

        If 'raw_values' is True, the values in the 'insert_values' dictionary
        are inserted directly into the query, rather than passed as SQL
        parameters. This provides a way to insert NULL and DEFAULT keywords
        into the query, for example.
        """
        placeholders, values = [], []
        for field, val in insert_values:
            placeholders.append((field, val))
            self.columns.append(field.column)
            values.append(val)
        if raw_values:
            self.values.extend([(None, v) for v in values])
        else:
            self.params += tuple(values)
            self.values.extend(placeholders)

class DateQuery(Query):
    """
    A DateQuery is a normal query, except that it specifically selects a single
    date field. This requires some special handling when converting the results
    back to Python objects, so we put it in a separate class.
    """

    compiler = 'SQLDateCompiler'

    def add_date_select(self, field_name, lookup_type, order='ASC'):
        """
        Converts the query into a date extraction query.
        """
        try:
            result = self.setup_joins(
                field_name.split(LOOKUP_SEP),
                self.get_meta(),
                self.get_initial_alias(),
                False
            )
        except FieldError:
            raise FieldDoesNotExist("%s has no field named '%s'" % (
                self.model._meta.object_name, field_name
            ))
        field = result[0]
        assert isinstance(field, DateField), "%r isn't a DateField." \
                % field.name
        alias = result[3][-1]
        select = Date((alias, field.column), lookup_type)
        self.select = [select]
        self.select_fields = [None]
        self.select_related = False # See #7097.
        self.set_extra_mask([])
        self.distinct = True
        self.order_by = order == 'ASC' and [1] or [-1]

        if field.null:
            self.add_filter(("%s__isnull" % field_name, False))

class AggregateQuery(Query):
    """
    An AggregateQuery takes another query as a parameter to the FROM
    clause and only selects the elements in the provided list.
    """

    compiler = 'SQLAggregateCompiler'

    def add_subquery(self, query, using):
        self.subquery, self.sub_params = query.get_compiler(using).as_sql(with_col_aliases=True)

class BatchPool(object):
    def __init__(self, size, batch_size):
        self.max_size = size
        self.max_batch_size = batch_size

        self.reset()

    def reset(self):
        self.pool = []
        self.pool_size = 0
        self.batches_sizes = []

    def append(self, instance, raw=False):
        if raw:
            groups = []
        else:
            groups = instance.get_parents_cascade()
        groups.append({instance.__class__: None})

        for idx, group in enumerate(groups):
            try:
                self.pool[idx]
            except IndexError:
                self.pool.append([])
                self.batches_sizes.append(0)

            for cls, field in group.items():
                self.pool[idx].append((instance, cls, field, raw))

            group_len = len(group)
            self.pool_size += group_len
            self.batches_sizes[idx] += group_len

    def is_full(self):
        if self.pool_size >= self.max_size:
            return True
        for batch_size in self.batches_sizes:
            if batch_size >= self.max_batch_size:
                return True
        return False

    def reverse(self):
        self.pool.reverse()

    def __iter__(self):
        return iter(self.pool)

class BatchQueryStub(object):
    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        pass

    def save(self, instance, **kwargs):
        instance.save(**kwargs)

    def delete(self, instance, **kwargs):
        instance.delete(**kwargs)

    def flush(self):
        pass

class BatchQuery(object):
    compiler = 'SQLBatchCompiler'

    def __init__(self, pool_size=None, batch_size=None,
                 save_pool_size=None, save_batch_size=None,
                 delete_pool_size=None, delete_batch_size=None,
                 using=DEFAULT_DB_ALIAS, **kwargs):
        self.using = using
        self.connection = connections[using]
        self.compiler = self.connection.ops.compiler(self.compiler)(self, self.connection, using,
                                                                    **kwargs)
        pool_size = pool_size or self.connection.features.batch_pool_size
        batch_size = batch_size or self.connection.features.batch_size

        save_pool_size = save_pool_size or pool_size
        save_batch_size = save_batch_size or batch_size
        self.save_pool = BatchPool(size=save_pool_size, batch_size=save_batch_size)

        delete_pool_size = delete_pool_size or pool_size
        delete_batch_size = delete_batch_size or batch_size
        self.delete_pool = BatchPool(size=delete_pool_size, batch_size=delete_batch_size)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.flush()

    def save(self, instance, using=None, raw=False, **kwargs):
        instance.pre_save(instance.__class__, raw=raw, using=self.using)
        self.save_pool.append(instance, raw=raw)
        if self.save_pool.is_full():
            print 'flushing'
            self.flush_saves()

    def delete(self, instance, using=None, **kwargs):
        instance.pre_delete(instance.__class__, using=self.using)
        self.delete_pool.append(instance)
        if self.delete_pool.is_full():
            self.flush_deletes()

    def flush_saves(self):
        for instance_cls_field_raw_list in self.save_pool:
            instance_cls_values_raw_list = []
            for instance, cls, field, raw in instance_cls_field_raw_list:
                values = []
                for local_field in cls._meta.local_fields:
                    if raw:
                        value = getattr(self, local_field.attname)
                    else:
                        value = local_field.pre_save(instance, not instance._entity_exists)
                    value = local_field.get_db_prep_save(value, connection=self.connection)
                    values.append((local_field, value))
                instance_cls_values_raw_list.append((instance, cls, values, raw))

            pk_vals = self.compiler.batch_save(instance_cls_values_raw_list)

            for (instance, cls, field, raw), pk_val in zip(instance_cls_field_raw_list, pk_vals):
                setattr(instance, cls._meta.pk.attname, pk_val)

                if field:
                    setattr(instance, field.attname, instance._get_pk_val(cls._meta))

                created = (not instance._entity_exists)
                instance._entity_exists = True
                instance.post_save(cls, created=created, raw=raw,
                                   using=self.using)
        self.save_pool.reset()

    def flush_deletes(self):
        self.save_pool.reverse()
        for instance_cls_field_raw_list in self.delete_pool:
            instance_cls_list = [(instance, cls) for instance, cls, field, raw
                            in instance_cls_field_raw_list]
            self.compiler.batch_delete(instance_cls_list)

            for instance, cls, field, _ in instance_cls_field_raw_list:
                setattr(instance, cls._meta.pk.attname, None)
                instance._entity_exists = False

                if field:
                    setattr(self, field.attname, None)

                instance.post_delete(instance.__class__, using=self.using)
        self.delete_pool.reset()

    def flush(self):
        self.flush_saves()
        self.flush_deletes()

class BatchOperation(object):
    def __init__(self, queries_args={}):
        self.queries_args = queries_args
        self.queries = {}

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        for query in self.queries.values():
            query.flush()

    def get_query(self, instance, using=None):
        using = using or router.db_for_write(instance.__class__, instance=instance)
        connection = connections[using]

        if using not in self.queries:
            if using in self.queries_args:
                kwargs = self.queries_args[using]
            else:
                kwargs = {}

            kwargs['using'] = using

            if connection.features.supports_batching:
                cls = BatchQuery
            else:
                cls = BatchQueryStub
            self.queries[using] = cls(**kwargs)
        return self.queries[using]

    def save(self, instance, using=None, **kwargs):
        self.get_query(instance, using=using).save(instance, using=using, **kwargs)

    def delete(self, instance, using=None, **kwargs):
        self.get_query(instance, using=using).delete(instance, using=using, **kwargs)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.