123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- def query_as_dict(expression, field_type=None):
- """Seralizes gluon.dal.Query as dictionary.
-
- Converts a gluon.dal.Query or gluon.dal.Expression
- into a dictionary structure that can be pickled and
- stored in the session.
-
- Args:
- expression: gluon.dal.Query or gluon.dal.Expression
-
- Returns:
- Dictionary in the form {op:op, first:expression, second:expression}
- op: the query operation (eg, AND, EQ, GT)
- expression: either a dictionary (that expands a gluon Table,
- Field, Expression or Query object) or a base object such as
- a string or list.
-
- For example:
- >>>query = (db.comment.id.belongs((1,2,3))) & (db.webpage.title == 'FAQ')
- >>>print query_as_dict(query)
- "{'second': {'second': 'FAQ', 'first': {'table': 'webpage', 'fieldname': 'title',
- 'tablename': 'webpage'}, 'op': 'EQ'}, 'first': {'second': (1, 2, 3), 'first':
- {'table': 'comment', 'fieldname': 'id', 'tablename': 'comment'}, 'op': 'BELONGS'},
- 'op': 'AND'}"
- """
- from gluon.dal import Query, Expression, Table, Field
- if isinstance(expression, Field):
- tablename = expression._tablename
- return dict(tablename=expression._tablename,
- table = str(expression._table),
- fieldname = expression.name)
- elif isinstance(expression, (Expression, Query)):
- if not expression.second is None:
- return dict(op=expression.op.im_func.__name__,
- first=query_as_dict(expression.first),
- second=query_as_dict(expression.second))
- elif not expression.first is None:
- if not expression.op is None:
- return dict(op=expression.op.im_func.__name__,
- first=query_as_dict(expression.first),
- second=None) # eg '(person.title IS NULL)'
- else:
- return expression.first
- elif not isinstance(expression.op, str):
- return expression.op()
- else:
- return '(%s)' % expression.op
- elif field_type:
- return str(represent(expression,field_type))
- elif isinstance(expression,(list,tuple)):
- return expression
- elif isinstance(expression, Table):
- return dict(tablename=expression._tablename,
- table = str(expression))
- elif expression==None:
- return None
- else:
- return str(expression)
- def query_from_dict(db, query, out='Query'):
- """Builds gluon.dal.Query from dictionary structure.
-
- Args:
- db: gluon.dal.db object
- query: A dictionary in the form {op:op, first:expression, second:expression}
- as returned by query_as_dict()
- out: Set to 'Expression' for gluon.dal.Expression
- rather than Query.
-
- Returns:
- gluon.dal.Query or gluon.dal.Expression object
- """
- from gluon.dal import Expression, Query
- if out == 'Expression':
- out_class = Expression
- else:
- out_class = Query
- if type(query) == dict:
- if 'op' in query.keys():
- first = query_from_dict(db, query['first'], out=out)
- second = query_from_dict(db, query['second'], out=out)
- op = getattr(db._adapter, query['op'])
- return out_class(db, op, first=first, second=second)
- elif 'fieldname' in query.keys():
- if query['tablename'] == query['table']:
- return db[query['tablename']][query['fieldname']]
- else: # a table.field with alias
- return db[query['table']].with_alias(query['tablename'])[query['fieldname']]
- elif 'tablename' in query.keys():
- if query['tablename'] == query['table']:
- return db[query['tablename']]
- elif ' AS ' in query['table']: # a table with alias
- t = query['table'].split(' ')[0]
- return db[t].with_alias(query['tablename'])
- else:
- raise ValueError
- else:
- return query
- def process_views(views):
- import re
- from itertools import groupby
- pattern = re.compile('(\w+).(\w+)')
- keyfunc = lambda x: x[0]
- grouped_views = {}
- for view_name, sensors in views.iteritems():
- slist = []
- for sensor in sensors:
- m = pattern.match(sensor)
- slist.append((m.group(1), m.group(2)))
- sgroups = []
- for table, sgroup in groupby(slist, keyfunc):
- sgroups.append((table, [s[1] for s in sgroup]))
- grouped_views[view_name] = sgroups
- return grouped_views
|