Source

ytmanager / djangoappengine / db / compiler.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
from .db_settings import get_indexes

import datetime
import sys

from django.db.models.sql import aggregates as sqlaggregates
from django.db.models.sql.constants import LOOKUP_SEP, MULTI, SINGLE
from django.db.models.sql.where import AND, OR
from django.db.utils import DatabaseError, IntegrityError
from django.utils.tree import Node

from functools import wraps

from google.appengine.api.datastore import Entity, Query, MultiQuery, \
    Put, Get, Delete, Key
from google.appengine.api.datastore_errors import Error as GAEError
from google.appengine.api.datastore_types import Text, Category, Email, Link, \
    PhoneNumber, PostalAddress, Text, Blob, ByteString, GeoPt, IM, Key, \
    Rating, BlobKey

from djangotoolbox.db.basecompiler import NonrelQuery, NonrelCompiler, \
    NonrelInsertCompiler, NonrelUpdateCompiler, NonrelDeleteCompiler

import decimal

# Valid query types (a dictionary is used for speedy lookups).
OPERATORS_MAP = {
    'exact': '=',
    'gt': '>',
    'gte': '>=',
    'lt': '<',
    'lte': '<=',

    # The following operators are supported with special code below:
    'isnull': None,
    'in': None,
    'startswith': None,
    'range': None,
    'year': None,
}

NEGATION_MAP = {
    'gt': '<=',
    'gte': '<',
    'lt': '>=',
    'lte': '>',
    # TODO: support these filters
    #'exact': '!=', # this might actually become individual '<' and '>' queries
}

def safe_call(func):
    @wraps(func)
    def _func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except GAEError, e:
            raise DatabaseError, DatabaseError(str(e)), sys.exc_info()[2]
    return _func

class GAEQuery(NonrelQuery):
    # ----------------------------------------------
    # Public API
    # ----------------------------------------------
    def __init__(self, compiler, fields):
        super(GAEQuery, self).__init__(compiler, fields)
        self.inequality_field = None
        self.pk_filters = None
        self.excluded_pks = ()
        self.has_negated_exact_filter = False
        self.ordering = ()
        self.gae_ordering = []
        pks_only = False
        if len(fields) == 1 and fields[0].primary_key:
            pks_only = True
        self.db_table = self.query.get_meta().db_table
        self.pks_only = pks_only
        start_cursor = getattr(self.query, '_gae_start_cursor', None)
        end_cursor = getattr(self.query, '_gae_end_cursor', None)
        self.gae_query = [Query(self.db_table, keys_only=self.pks_only,
                                cursor=start_cursor, end_cursor=end_cursor)]

    # This is needed for debugging
    def __repr__(self):
        return '<GAEQuery: %r ORDER %r>' % (self.gae_query, self.ordering)

    @safe_call
    def fetch(self, low_mark, high_mark):
        query = self._build_query()
        executed = False
        if self.excluded_pks and high_mark is not None:
            high_mark += len(self.excluded_pks)
        if self.pk_filters is not None:
            results = self.get_matching_pk(low_mark, high_mark)
        else:
            if high_mark is None:
                kw = {}
                if low_mark:
                    kw['offset'] = low_mark
                results = query.Run(**kw)
                executed = True
            elif high_mark > low_mark:
                results = query.Get(high_mark - low_mark, low_mark)
                executed = True
            else:
                results = ()

        for entity in results:
            if isinstance(entity, Key):
                key = entity
            else:
                key = entity.key()
            if key in self.excluded_pks:
                continue
            yield self._make_entity(entity)

        if executed and not isinstance(query, MultiQuery):
            self.query._gae_cursor = query.GetCompiledCursor()

    @safe_call
    def count(self, limit=None):
        if self.pk_filters is not None:
            return len(self.get_matching_pk(0, limit))
        if self.excluded_pks:
            return len(list(self.fetch(0, 2000)))
        kw = {}
        if limit is not None:
            kw['limit'] = limit
        return self._build_query().Count(**kw)

    @safe_call
    def delete(self):
        if self.pk_filters is not None:
            keys = [key for key in self.pk_filters if key is not None]
        else:
            keys = self.fetch()
        if keys:
            Delete(keys)

    @safe_call
    def order_by(self, ordering):
        self.ordering = ordering
        for order in self.ordering:
            if order.startswith('-'):
                order, direction = order[1:], Query.DESCENDING
            else:
                direction = Query.ASCENDING
            if order == self.query.get_meta().pk.column:
                order = '__key__'
            self.gae_ordering.append((order, direction))

    # This function is used by the default add_filters() implementation
    @safe_call
    def add_filter(self, column, lookup_type, negated, db_type, value):
        if value in ([], ()):
            self.pk_filters = []
            return

        # Emulated/converted lookups
        if column == self.query.get_meta().pk.column:
            column = '__key__'
            db_table = self.query.get_meta().db_table
            if lookup_type in ('exact', 'in'):
                # Optimization: batch-get by key
                if self.pk_filters is not None:
                    raise DatabaseError("You can't apply multiple AND filters "
                                        "on the primary key. "
                                        "Did you mean __in=[...]?")
                if not isinstance(value, (tuple, list)):
                    value = [value]
                pks = [create_key(db_table, pk) for pk in value if pk]
                if negated:
                    self.excluded_pks = pks
                else:
                    self.pk_filters = pks
                return
            else:
                # XXX: set db_type to 'gae_key' in order to allow
                # convert_value_for_db to recognize the value to be a Key and
                # not a str. Otherwise the key would be converted back to a
                # unicode (see convert_value_for_db)
                db_type = 'gae_key'
                key_type_error = 'Lookup values on primary keys have to be' \
                                 'a string or an integer.'
                if lookup_type == 'range':
                    if isinstance(value,(list, tuple)) and not(isinstance(
                            value[0], (basestring, int, long)) and \
                            isinstance(value[1], (basestring, int, long))):
                        raise DatabaseError(key_type_error)
                elif not isinstance(value,(basestring, int, long)):
                    raise DatabaseError(key_type_error)
                # for lookup type range we have to deal with a list
                if lookup_type == 'range':
                    value[0] = create_key(db_table, value[0])
                    value[1] = create_key(db_table, value[1])
                else:
                    value = create_key(db_table, value)
        if lookup_type not in OPERATORS_MAP:
            raise DatabaseError("Lookup type %r isn't supported" % lookup_type)

        # We check for negation after lookup_type isnull because it
        # simplifies the code. All following lookup_type checks assume
        # that they're not negated.
        if lookup_type == 'isnull':
            if (negated and value) or not value:
                # TODO/XXX: is everything greater than None?
                op = '>'
            else:
                op = '='
            value = None
        elif negated and lookup_type == 'exact':
            if self.has_negated_exact_filter:
                raise DatabaseError("You can't exclude more than one __exact "
                                    "filter")
            self.has_negated_exact_filter = True
            self._combine_filters(column, db_type,
                                  (('<', value), ('>', value)))
            return
        elif negated:
            try:
                op = NEGATION_MAP[lookup_type]
            except KeyError:
                raise DatabaseError("Lookup type %r can't be negated" % lookup_type)
            if self.inequality_field and column != self.inequality_field:
                raise DatabaseError("Can't have inequality filters on multiple "
                    "columns (here: %r and %r)" % (self.inequality_field, column))
            self.inequality_field = column
        elif lookup_type == 'in':
            # Create sub-query combinations, one for each value
            if len(self.gae_query) * len(value) > 30:
                raise DatabaseError("You can't query against more than "
                                    "30 __in filter value combinations")
            op_values = [('=', v) for v in value]
            self._combine_filters(column, db_type, op_values)
            return
        elif lookup_type == 'startswith':
            self._add_filter(column, '>=', db_type, value)
            if isinstance(value, str):
                value = value.decode('utf8')
            if isinstance(value, Key):
                value = list(value.to_path())
                if isinstance(value[-1], str):
                    value[-1] = value[-1].decode('utf8')
                value[-1] += u'\ufffd'
                value = Key.from_path(*value)
            else:
                value += u'\ufffd'
            self._add_filter(column, '<=', db_type, value)
            return
        elif lookup_type in ('range', 'year'):
            self._add_filter(column, '>=', db_type, value[0])
            op = '<=' if lookup_type == 'range' else '<'
            self._add_filter(column, op, db_type, value[1])
            return
        else:
            op = OPERATORS_MAP[lookup_type]

        self._add_filter(column, op, db_type, value)

    # ----------------------------------------------
    # Internal API
    # ----------------------------------------------
    def _add_filter(self, column, op, db_type, value):
        for query in self.gae_query:
            key = '%s %s' % (column, op)
            value = self.convert_value_for_db(db_type, value)
            if key in query:
                existing_value = query[key]
                if isinstance(existing_value, list):
                    existing_value.append(value)
                else:
                    query[key] = [existing_value, value]
            else:
                query[key] = value

    def _combine_filters(self, column, db_type, op_values):
        gae_query = self.gae_query
        combined = []
        for query in gae_query:
            for op, value in op_values:
                self.gae_query = [Query(self.db_table,
                                        keys_only=self.pks_only)]
                self.gae_query[0].update(query)
                self._add_filter(column, op, db_type, value)
                combined.append(self.gae_query[0])
        self.gae_query = combined

    def _make_entity(self, entity):
        if isinstance(entity, Key):
            key = entity
            entity = {}
        else:
            key = entity.key()

        entity[self.query.get_meta().pk.column] = key
        return entity

    @safe_call
    def _build_query(self):
        if len(self.gae_query) > 1:
            return MultiQuery(self.gae_query, self.gae_ordering)
        query = self.gae_query[0]
        query.Order(*self.gae_ordering)
        return query

    def get_matching_pk(self, low_mark=0, high_mark=None):
        if not self.pk_filters:
            return []

        results = [result for result in Get(self.pk_filters)
                   if result is not None and
                       self.matches_filters(result)]
        if self.ordering:
            results.sort(cmp=self.order_pk_filtered)
        if high_mark is not None and high_mark < len(results) - 1:
            results = results[:high_mark]
        if low_mark:
            results = results[low_mark:]
        return results

    def order_pk_filtered(self, lhs, rhs):
        left = dict(lhs)
        left[self.query.get_meta().pk.column] = lhs.key().to_path()
        right = dict(rhs)
        right[self.query.get_meta().pk.column] = rhs.key().to_path()
        return self._order_in_memory(left, right)

    def matches_filters(self, entity):
        item = dict(entity)
        pk = self.query.get_meta().pk
        value = self.convert_value_from_db(pk.db_type(connection=self.connection),
            entity.key())
        item[pk.column] = value
        result = self._matches_filters(item, self.query.where)
        return result

class SQLCompiler(NonrelCompiler):
    """
    A simple App Engine query: no joins, no distinct, etc.
    """
    query_class = GAEQuery

    def convert_value_from_db(self, db_type, value):
        if isinstance(value, (list, tuple)) and len(value) and \
                db_type.startswith('ListField:'):
            db_sub_type = db_type.split(':', 1)[1]
            value = [self.convert_value_from_db(db_sub_type, subvalue)
                     for subvalue in value]

        # the following GAE database types are all unicode subclasses, cast them
        # to unicode so they appear like pure unicode instances for django
        if isinstance(value, basestring) and value and db_type.startswith('decimal'):
            value = decimal.Decimal(value)
        elif isinstance(value, (Category, Email, Link, PhoneNumber, PostalAddress,
                Text, unicode)):
            value = unicode(value)
        elif isinstance(value, Blob):
            value = str(value)
        elif isinstance(value, str):
            # always retrieve strings as unicode (it is possible that old datasets
            # contain non unicode strings, nevertheless work with unicode ones)
            value = value.decode('utf-8')
        elif isinstance(value, Key):
            # for now we do not support KeyFields thus a Key has to be the own
            # primary key
            # TODO: GAE: support parents via GAEKeyField
            assert value.parent() is None, "Parents are not yet supported!"
            if db_type == 'integer':
                if value.id() is None:
                    raise DatabaseError('Wrong type for Key. Expected integer, found'
                        'None')
                else:
                    value = value.id()
            elif db_type == 'text':
                if value.name() is None:
                    raise DatabaseError('Wrong type for Key. Expected string, found'
                        'None')
                else:
                    value = value.name()
            else:
                raise DatabaseError("%s fields cannot be keys on GAE" % db_type)
        elif db_type == 'date' and isinstance(value, datetime.datetime):
            value = value.date()
        elif db_type == 'time' and isinstance(value, datetime.datetime):
            value = value.time()
        return value

    def convert_value_for_db(self, db_type, value):
        if isinstance(value, unicode):
            value = unicode(value)
        elif isinstance(value, str):
            value = str(value)
        elif isinstance(value, (list, tuple)) and len(value) and \
                db_type.startswith('ListField:'):
            db_sub_type = db_type.split(':', 1)[1]
            value = [self.convert_value_for_db(db_sub_type, subvalue)
                     for subvalue in value]
        elif isinstance(value, decimal.Decimal) and db_type.startswith("decimal:"):
            value = self.connection.ops.value_to_db_decimal(value, *eval(db_type[8:]))

        if db_type == 'gae_key':
            return value
        elif db_type == 'longtext':
            # long text fields cannot be indexed on GAE so use GAE's database
            # type Text
            value = Text((isinstance(value, str) and value.decode('utf-8')) or value)
        elif db_type == 'text':
            value = (isinstance(value, str) and value.decode('utf-8')) or value
        elif db_type == 'blob':
            value = Blob(value)
        elif type(value) is str:
            # always store unicode strings
            value = value.decode('utf-8')
        elif db_type == 'date' or db_type == 'time' or db_type == 'datetime':
            # here we have to check the db_type because GAE always stores datetimes
            value = to_datetime(value)
        return value

class SQLInsertCompiler(NonrelInsertCompiler, SQLCompiler):
    @safe_call
    def insert(self, data, return_id=False):
        gae_data = {}
        opts = self.query.get_meta()
        indexes = get_indexes().get(self.query.model, {})
        unindexed_fields = indexes.get('unindexed', ())
        unindexed_cols = [opts.get_field(name).column
                          for name in unindexed_fields]
        kwds = {'unindexed_properties': unindexed_cols}
        for column, value in data.items():
            if column == opts.pk.column:
                if isinstance(value, basestring):
                    kwds['name'] = value
                else:
                    kwds['id'] = value
            elif isinstance(value, (tuple, list)) and not len(value):
                # gae does not store emty lists (and even does not allow passing empty
                # lists to Entity.update) so skip them
                continue
            else:
                gae_data[column] = value

        entity = Entity(self.query.get_meta().db_table, **kwds)
        entity.update(gae_data)
        key = Put(entity)
        return key.id_or_name()

class SQLUpdateCompiler(NonrelUpdateCompiler, SQLCompiler):
    pass

class SQLDeleteCompiler(NonrelDeleteCompiler, SQLCompiler):
    pass

def to_datetime(value):
    """Convert a time or date to a datetime for datastore storage.

    Args:
    value: A datetime.time, datetime.date or string object.

    Returns:
    A datetime object with date set to 1970-01-01 if value is a datetime.time
    A datetime object with date set to value.year - value.month - value.day and
    time set to 0:00 if value is a datetime.date
    """

    if value is None:
        return value
    elif isinstance(value, datetime.datetime):
        return value
    elif isinstance(value, datetime.date):
        return datetime.datetime(value.year, value.month, value.day)
    elif isinstance(value, datetime.time):
        return datetime.datetime(1970, 1, 1, value.hour, value.minute,
            value.second, value.microsecond)

def create_key(db_table, value):
    if isinstance(value, (int, long)) and value < 1:
        return None
    return Key.from_path(db_table, value)