8e25ed9e4ca84d2a3c232c54a2be2b099c2d1890
[unfold.git] / engine / manifoldquery.py
1 import json
2
3 # xxx php has uniqid, need to find a module for that
4 counter=1
5 def uniqid (): global counter; counter += 1; return counter
6
7 class ManifoldQuery:
8
9     def __init__ (self, action=None, method=None, timestamp='now',
10                   filters=[], params=[], fields=[],
11                   sort=None, limit=None, offset=None,
12                   ):
13         self.uuid=uniqid()
14         # settable
15         self.action=action
16         self.method=method
17         self.timestamp=timestamp
18         self.filters=filters
19         self.params=params
20         self.fields=fields
21         self.sort=sort
22         self.limit=limit
23         self.offset=offset
24         # internal data
25         self.analyzed_query=None
26         self.subqueries = {}
27
28     def to_json (self):
29         uuid=self.uuid
30         a=self.action
31         m=self.method
32         t=self.timestamp
33         f=json.dumps (self.filters)
34         p=json.dumps (self.params)
35         c=json.dumps (self.fields)
36         # xxx unique can be removed, but for now we pad the js structure
37         unique=0
38
39         aq = self.analyzed_query.to_json() if self.analyzed_query else 'null'
40         # subqueries is a dictionary method:query
41         if not self.subqueries: 
42             sq="{}"
43         else:
44             sq=", ".join ( [ "'%s':%s" % (method, subquery.to_json())
45                       for (method, subquery) in self.subqueries.iteritems()])
46             sq="{%s}"%sq
47         
48         return """ new Query('%(a)s', '%(m)s', '%(t)s', %(f)s, %(p)s, %(c)s, %(unique)s, '%(uuid)s', %(aq)s, %(sq)s)"""%locals()
49     
50     # 4amine
51     # xxx
52     # this should build an object from a dict as received from javascript
53     # to see an example just look at the server's output
54     # incoming POST <QueryDict: {u'query[method]': [u'slice'], u'query[fields][]': [u'slice_hrn'], u'query[ts]': [u'latest'], u'query[action]': [u'get']}>
55     def fill_from_dict (self, d):
56         for key in d.keys():
57            for arg in ['action', 'method', 'filters', 'fields', 'timestamp', 'params']:
58                 if arg in key:
59                     # dirty hack around fields; fields must be a list
60                     if arg == 'fields': 
61                         setattr(self, arg, [d[key]])
62                     else: 
63                         setattr(self, arg, d[key])
64                     break
65