266 'There is no "%(name)s" where %(pairs)s.') % { |
266 'There is no "%(name)s" where %(pairs)s.') % { |
267 'name': self._name, 'pairs': joined_pairs} |
267 'name': self._name, 'pairs': joined_pairs} |
268 |
268 |
269 raise out_of_band.Error(msg, status=404) |
269 raise out_of_band.Error(msg, status=404) |
270 |
270 |
271 def getForFields(self, filter=None, unique=False, limit=1000, offset=0): |
271 def getForFields(self, filter=None, unique=False, |
|
272 limit=1000, offset=0, order=None): |
272 """Returns all entities that have the specified properties. |
273 """Returns all entities that have the specified properties. |
273 |
274 |
274 Args: |
275 Args: |
275 filter: a dict for the properties that the entities should have |
276 filter: a dict for the properties that the entities should have |
276 unique: if set, only the first item from the resultset will be returned |
277 unique: if set, only the first item from the resultset will be returned |
277 limit: the amount of entities to fetch at most |
278 limit: the amount of entities to fetch at most |
278 offset: the position to start at |
279 offset: the position to start at |
279 """ |
280 order: a list with the sort order |
280 |
281 """ |
|
282 |
|
283 if not filter: |
|
284 filter = {} |
281 if unique: |
285 if unique: |
282 limit = 1 |
286 limit = 1 |
283 |
287 if not order: |
284 if filter: |
288 order = [] |
285 format_eq = '%(key)s = :%(num)d' |
289 |
286 format_in = '%(key)s IN (%(values)s)' |
290 orderset = set([i.strip('-') for i in order]) |
287 |
291 if len(orderset) != len(order): |
288 n = 1 |
292 raise InvalidArgumentError |
289 conditionals = [] |
293 |
290 args = [] |
294 q = db.Query(self._model) |
291 |
295 |
292 for key, value in filter.iteritems(): |
296 for key, value in filter.iteritems(): |
293 if isinstance(value, list): |
297 if isinstance(value, list): |
294 count = len(value) |
298 op = '%s IN' % key |
295 args.extend(value) |
299 q.filter(op, value) |
296 values = ', '.join([':%d' % i for i in range(n, n + count)]) |
300 else: |
297 sub = format_in % {'key': key, 'values': values} |
301 q.filter(key, value) |
298 n = n + count |
302 |
299 else: |
303 for key in order: |
300 sub = format_eq % {'key': key, 'num': n} |
304 q.order(key) |
301 args.append(value) |
|
302 n = n + 1 |
|
303 conditionals.append(sub) |
|
304 |
|
305 joined_pairs = ' AND '.join(conditionals) |
|
306 condition = 'WHERE ' + joined_pairs |
|
307 |
|
308 q = self._model.gql(condition, *args) |
|
309 else: |
|
310 q = self._model.all() |
|
311 |
305 |
312 result = q.fetch(limit, offset) |
306 result = q.fetch(limit, offset) |
313 |
307 |
314 if unique: |
308 if unique: |
315 return result[0] if result else None |
309 return result[0] if result else None |