trac-gviz / trac-dev / gviz / tracgviz / gvizql.py

Olemis Lang 49a0635 


















































































































































































































































































































































































































Olemis Lang b244f16 

Olemis Lang 49a0635 





























































































































































































































































Olemis Lang 101ee06 




























































Olemis Lang 49a0635 
Olemis Lang 101ee06 




Olemis Lang 49a0635 
Olemis Lang 101ee06 



Olemis Lang 49a0635 
Olemis Lang 101ee06 




Olemis Lang b244f16 
Olemis Lang 101ee06 

  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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
#!/usr/bin/env python

# Copyright 2009-2011 Olemis Lang <olemis at gmail.com>
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

r"""Basic features needed to support Google Visualization Query Language
(aka. GVizQL).

Copyright 2009-2011 Olemis Lang <olemis at gmail.com>
Licensed under the Apache License, Version 2.0 
"""
__author__ = 'Olemis Lang'

__all__ = 'prepare_ql_data', 'GVizQLClauseHandler', 'GVizQLParser', \
          'defaultParser'
__metaclass__ = type

from itertools import islice, izip
from pygments.lexer import RegexLexer
from pygments.filter import Filter
from pygments.token import *
from re import compile
from weakref import proxy

#------------------------------------------------------
#   GVizQL clause handlers 
#------------------------------------------------------

class GVizQLClauseType(type):
  r"""Keep track of all GVizQL clause handlers installed in the 
  system, syntax order ...
  
  >>> ','.join(ct.get_props('keyw') for ct in GVizQLClauseType.iterparse())
  'select,from,where,group by,pivot,order by,limit,offset,label,format,options'
  
  ... as well as evaluation order.
  
  >>> ','.join(ct.get_props('keyw') for ct in GVizQLClauseType.itereval())
  'from,group by,pivot,where,order by,offset,limit,select,format,options,label'
  """
  CLAUSE_CACHE = dict()
  SYNTAX_ORDER = list()
  EVAL_ORDER = list()
  PROPS = ('idx_syntax', 'idx_eval', 'keyw')
  
  def __new__(cls, name, bases, suite):
    r"""Keep track of all GVizQL clause handlers installed in the 
    system, as well as evaluation order.
    """
    try:
      abstract = suite['__abstract__']
      del suite['__abstract__']
    except KeyError:
      abstract = False
    
    @classmethod
    def get_props(cls, propnm):
      try:
        return self._PROPS[propnm]
      except KeyError, exc:
        raise ValueError('Unsupported property %s', exc.message)
    suite['get_props'] = get_props
    
    self = super(GVizQLClauseType, cls).__new__(cls, name, bases, suite)
    if not abstract:
      cnm = self.get_props('keyw')
      GVizQLClauseType.CLAUSE_CACHE[cnm] = self
      GVizQLClauseType.SYNTAX_ORDER.append(self)
      GVizQLClauseType.SYNTAX_ORDER.sort(None, \
                                    lambda x: x.get_props('idx_syntax'))
      GVizQLClauseType.EVAL_ORDER.append(self)
      GVizQLClauseType.EVAL_ORDER.sort(None, \
                                    lambda x: x.get_props('idx_eval'))
    return self
  
  @staticmethod
  def itereval():
    r"""Iterate over GVizQL clause handlers following evaluation order.
    """
    return iter(GVizQLClauseType.EVAL_ORDER)
  
  @staticmethod
  def iterparse():
    r"""Iterate over GVizQL clause handlers following syntax order.
    """
    return iter(GVizQLClauseType.SYNTAX_ORDER)
  
  @staticmethod
  def clauses():
    r"""Retrieved all the keywords identifying different clauses 
    supported in the system.
    """
    return GVizQLClauseType.CLAUSE_CACHE.keys()

class GVizQLClauseHandler:
  r"""Objects used to define syntax and retrieve items inside a 
  clause. It's also responsible of performing the transformations 
  dictated by this clause on a data set.
  
  Instances of this class have to override the following fields:
    - `_PROPS` :      a static dictionary containing the following keys
      * `idx_syntax`    a number indicating the relative syntantic 
                        order of this clause.
      * `idx_eval`      a number indicating the relative order of 
                        this clause at evaluation time.
      * `keyw`          the keyword introducing (i.e. identifying) 
                        this clause.
    - `transform` :   override this method in order to apply the 
                      transformations specified by the client  in the 
                      corresponding clause to the input result set.
  """
  __metaclass__ = GVizQLClauseType
  __abstract__ = True
  
  ERR_MSGS = {
      'PARSING' : "%(clause)s clause is not supported yet.",
      'EVAL' :    "Unable to evaluate %(clause)s clause. " \
                  "Either the whole clause or an specific feature " \
                  "is not supported yet."
    }
  
  def unsupported(self, at='PARSING', **vals):
    r"""Indicate that this clause is not supported yet.
    """
    vals['clause'] = self.get_props('keyw').upper()
    msg = self.ERR_MSGS.get(at, '') % vals
    raise GVizUnsupportedQueryOp(msg)
  
  def transform(self, schema, data):
    r"""Transform the result set as dictated by the clause included 
    in the GViz QL expression provided by the client. This 
    transformation *SHOULD* be performed by using iterators.
    
    Note: Default behavior is to indicate that the clause is not 
    supported.
    """
    self.unsupported(at='EVAL')

class GVizSelectClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 0, 'idx_eval': 7, 'keyw' : 'select'}
  KEYWORDS = ('select',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in SELECT clause.
    """
    tkn, val = ctx.stream.next()
    if tkn is Name.Other and val == '*':
      self.cols = None
      tkn, val = ctx.stream.next()
    elif tkn is Name.Variable:
      if val.startswith('`'):
        val = val[1:-1]
      self.cols = cols = [val]
      for tkn, val in ctx.stream :
        if tkn is Punctuation and val == ',' :
          tkn, val = ctx.stream.next()
          if tkn is Name.Variable :     # FIXME: Just column names so far
            if val.startswith('`'):
              val = val[1:-1]
            cols.append(val)
          elif tkn in (Name.Function, Name.Builtin):
            raise GVizUnsupportedQueryOp("Scalar and aggregate functions " \
                                          "not supported yet : token %s" % \
                                          (val,))
          else:
            raise GVizInvalidQuery("Syntax error or unsupported " \
                                    "feature. Unexpected token %s." \
                                                            % (val,))
        else:
          break
    elif tkn in (Name.Function, Name.Builtin):
      raise GVizUnsupportedQueryOp("Scalar and aggregate functions " \
                                    "not supported yet : token %s" % \
                                    (val,))
    else:
      if tkn is Whitespace and val == '\n' :
        val = '<EOL>'
      raise GVizInvalidQuery("Syntax error or unsupported " \
                              "feature. Unexpected token %s." % (val,))
  
  def transform(self, schema, data):
    r"""Arrange values considering the given column order.
    """
    cols = self.cols
    if cols is None:
      return schema, data
    else:
      idxmap = [None] * len(cols)
      schcols = dict([col[0], i] for i, col in enumerate(schema))
      for i, colnm in enumerate(cols):
        try:
          idxmap[i] = schcols[colnm]
        except KeyError, exc:
          raise GVizInvalidQuery("Unable to evaluate SELECT clause. " \
                                  "Unknown column %s." % (exc.message,))
      new_schema = [schema[i] for i in idxmap]
      new_data = ([row[i] for i in idxmap] for row in data)
      return new_schema, new_data

class GVizFromClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 1, 'idx_eval': 0, 'keyw' : 'from'}
  KEYWORDS = ('from',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in FROM clause.
    """
    tkn, val = ctx.stream.next()
    if tkn is Name.Variable :
      if val.startswith('`'):
        val = val[1:-1]
      self.basetable = val
      ctx.stream.next()
    else :
      raise GVizInvalidQuery("Syntax error: Table name expected but" \
                              " %s found." % (val,))
  def transform(self, schema, data):
    r"""Notify that base table has not been processed by data source. 
    This is made this way since it may hide a bug in the underlying 
    data source implementation.
    
    FROM clause is irrevelevant for transformations. This clause is 
    available so that the underlying data sources be able to handle 
    it. This feature will be supported in upcoming versions.
    """
    raise GVizInvalidQuery("Unable to evaluate FROM clause. " \
                              "Data source doesn't contain base " \
                              "table %s." % (self.basetable,))

class GVizWhereClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 2, 'idx_eval': 3, 'keyw' : 'where'}
  KEYWORDS = ('where',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in WHERE clause.
    """
    self.unsupported()

class GVizGroupByClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 3, 'idx_eval': 1, 'keyw' : 'group by'}
  KEYWORDS = ('group', 'by')
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in GROUP BY clause.
    """
    self.unsupported()

class GVizPivotClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 4, 'idx_eval': 2, 'keyw' : 'pivot'}
  KEYWORDS = ('pivot',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in the SELECT clause.
    """
    self.unsupported()

class GVizOrderByClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 5, 'idx_eval': 4, 'keyw' : 'order by'}
  KEYWORDS = ['asc', 'desc', 'order', 'by']
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in the SELECT clause.
    """
    self.unsupported()

class GVizLimitClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 6, 'idx_eval': 6, 'keyw' : 'limit'}
  KEYWORDS = ('limit',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in the SELECT clause.
    """
    tkn, val = ctx.stream.next()
    if tkn is Number.Integer :
      self.cnt = int(val)
      ctx.stream.next()
    else :
      raise GVizInvalidQuery("Syntax error: Integer number expected " \
                              "but %s found." % (val,))
  
  def transform(self, schema, data):
    r"""Retrieve no more than `cnt` items.
    """
    return schema, islice(data, self.cnt)

class GVizOffsetClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 7, 'idx_eval': 5, 'keyw' : 'offset'}
  KEYWORDS = ('offset',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in the SELECT clause.
    """
    tkn, val = ctx.stream.next()
    if tkn is Number.Integer :
      self.skip = int(val)
      ctx.stream.next()
    else :
      raise GVizInvalidQuery("Syntax error: Integer number expected " \
                              "but %s found." % (val,))
  
  def transform(self, schema, data):
    r"""Skip the number of items determined by `skip` attribute.
    """
    return schema, islice(data, self.skip, None)

class GVizLabelClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 8, 'idx_eval': 10, 'keyw' : 'label'}
  KEYWORDS = ('label',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in the SELECT clause.
    """
    self.labels = labels = []
    tkn, val = Punctuation, ','               # Enter the cycle initially
    while tkn is Punctuation and val == ',':
      tkn, val = ctx.stream.next()
      if tkn is Name.Variable :
        if val.startswith('`'):
          val = val[1:-1]
        colnm = val
        tkn, val = ctx.stream.next()
        if tkn in [String.Single, String.Double]:
          val = val[1:-1]                         # Remove quotes
          labels.append((colnm, val.encode('utf-8', 'ignore')))
        else :
          raise GVizInvalidQuery("Syntax error: String constant " \
                                "expected but %s found." % (val,))
        tkn, val = ctx.stream.next()
      else :
        raise GVizInvalidQuery("Syntax error: Column name expected " \
                                "but %s found." % (val,))
  
  def transform(self, schema, data):
    r"""(Add | modify) the schema in order to (include | update) 
    column labels.
    
    Note: The process is not aborted if a label for a missing column 
          is specified.
    """
    labels = dict(self.labels)
    new_schema = [col[0] in labels and col[:2] + (labels[col[0]],) or col \
                    for col in schema]
    return new_schema, data

class GVizFormatClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 9, 'idx_eval': 8, 'keyw' : 'format'}
  KEYWORDS = ('format',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in the SELECT clause.
    """
    self.unsupported()

class GVizOptionsClause(GVizQLClauseHandler):
  _PROPS = {'idx_syntax' : 10, 'idx_eval': 9, 'keyw' : 'options'}
  KEYWORDS = ('options',)
  
  def __init__(self, ctx):
    r"""Initialize the expression using the enclosing parsing context
    (see docs for `GVizQLParsingContext`). Try to parse the items 
    in the SELECT clause.
    """
    self.unsupported()

#------------------------------------------------------
#   GVizQL parsing and compilation
#------------------------------------------------------

class GVizQLParser(RegexLexer):
  r"""Objects used to parse GVizQL expressions. 
  """
  GVIZ_QL_KEYWS = [k for ct in GVizQLClauseType.iterparse() \
                        for k in ct.KEYWORDS]
  GVIZ_QL_OPS = 'and,or,is,not,contains,starts with,ends with,matches,' \
        'like'.split(',')
  GVIZ_QL_FUNCS = 'max min count avg sum'.split()
  GVIZ_QL_CPREF = 'date datetime timeofday timestamp'.split()
  GVIZ_QL_CONST = 'true false null'.split()
  GVIZ_QL_TOKENS = {                # Keywords generated in update_syntax
                                    # Identifiers generated in update_syntax
        'int' : '(?:\d+)',          # Integer numbers
        'str' : r"""(?:(?:\'[^']*\')|(?:\"[^"]*\"))""", # Strings
        'number' : '(?:+|-)\d*(?:\.\d+)?',              # Numbers
        'bool' : '(?:true|false)',  # Boolean constants
        'date' : '(?:true|false)',
      }
  tokens = {
        'root' : [
            (r'[(,)]', Punctuation),
            (r'(?:<=)|(?:>=)|(?:!=)|(?:<>)', Operator),
            (r'[-+*/<>=]', Operator),
            (r'(?=date\s)', Whitespace, 'date'),
            (r'(?=timeofday\s)', Whitespace, 'tod'),
            (r'(?=(?:datetime|timestamp)\s)', Whitespace, 'dt'),
            (r'`(?:\w|\s)+`', Name.Variable),
            (r'`.*`', Generic.Error),
            (r'`[^`]*(?=$)', Generic.Error),
            (r'\d*\.\d+(?=[^a-zA-Z_])', Number),
            (r'\d+(?=[^a-zA-Z_])', Number.Integer),
            (r'(?:\d*\.)?\d+(?:[a-zA-Z_]\w*)', Generic.Error),
            (r'(?=\w)', Whitespace, 'alpha'),
            (r'(?:\d+)(?=[.a-zA-Z_])', Generic.Error),
            (r"\'[^']*\'", String.Single),
            (r'\"[^"]*\"', String.Double),
            (r"\'[^']*(?=$)", Generic.Error),
            (r'\"[^"]*(?=$)', Generic.Error),
            (r'\s+', Whitespace),
            (r'.', Generic.Error),
          ],
        'date' : [
            (r"date\s+\'\d{4}-\d{1,2}-\d{1,2}\'", Literal.Date, '#pop'),
            (r'date\s+\"\d{4}-\d{1,2}-\d{1,2}\"', Literal.Date, '#pop'),
            (r"date\s+", Generic.Error, '#pop')
          ],
        'tod' : [
            (r"timeofday\s+\'\d{1,2}(?:\:\d{1,2}){2}(?:\.\d{1-3})?\'", \
                Literal.Date, '#pop'),
            (r'timeofday\s+\"\d{1,2}(?:\:\d{1,2}){2}(?:\.\d{1-3})?\"', \
                Literal.Date, '#pop'),
            (r"timeofday\s+", Generic.Error, '#pop')
          ],
        'dt' : [
            (r'(?:datetime|timestamp)\s+\"\d{4}-\d{1,2}-\d{1,2}\ ' \
             r'\d{1,2}(?:\:\d{1,2}){2}(?:\.\d{3})?\"', \
                Literal.Date, '#pop'),
            (r"(?:datetime|timestamp)\s+\'\d{4}-\d{1,2}-\d{1,2}\ " \
             r"\d{1,2}(?:\:\d{1,2}){2}(?:\.\d{3})?\'", \
                Literal.Date, '#pop'),
            (r"(?:datetime|timestamp)\s+", Generic.Error, '#pop')
          ],
        'alpha' : [
            (r'(?:%s)(?=\s|$)' % '|'.join(GVIZ_QL_CONST), \
                Keyword.Constant, '#pop'),
            (r'(?:(?:%s)|(?:is\ not))(?=\s)' % '|'.join(GVIZ_QL_OPS), \
                Operator.Word, '#pop'),
            ('(?:%s)(?=\W)' % '|'.join(GVizQLClauseType.clauses()), \
                Keyword.Reserved, '#pop'), 
            ('(?:%s)(?=\W)' % '|'.join(GVIZ_QL_KEYWS), 
                Keyword, '#pop'), 
            ('(?:%s)(?=\W)' % '|'.join(GVIZ_QL_FUNCS), 
                Name.Builtin, '#pop'), 
            (r'[a-zA-Z]\w*(?=\()', Name.Function, '#pop'),
            (r'[a-zA-Z]\w*', Name.Variable, '#pop'),
          ],
      }
  
  def __init__(self, *args, **kwds):
    super(GVizQLParser, self).__init__(*args, **kwds)
    self.noisy = True
  
  def parse(self, tq):
    r"""Parse a GVizQL expression.
    
    @param tq                       the GViz QL expression.
    @return                         an instance 
    @throw GVizInvalidQuery         if a syntax error or other error 
                                    is detected in the input string.
    @throw GVizUnsupportedQueryOp   if the GViz QL query expression 
                                    contains a clause or feature 
                                    that's not supported yet.
    """
    global GVizUnsupportedQueryOp, GVizInvalidQuery
    from api import GVizUnsupportedQueryOp as GU, GVizInvalidQuery as GI
    GVizUnsupportedQueryOp, GVizInvalidQuery = GU, GI
    
    tkns = iter(self.get_tokens(tq))
    try:
      tkn, val = tkns.next()
    except StopIteration:
      raise GVizInvalidQuery("No token found: empty string ?")
    else:
      order = None
      expr = GVizQLExpression()
      ch = None
      try:
        while True:         # Try to parse the next clause
          if tkn is Whitespace and val == '\n':
            break
          elif tkn is not Keyword.Reserved:   # Check for a valid clause 
            last = ch.get_props('keyw')
            raise GVizInvalidQuery("Invalid token %s found %s: " \
                                    "Clause name expected." % \
                                        (val, ch and 'after ' + last or ''))
          clause_type = GVizQLClauseType.CLAUSE_CACHE[val]
          clause_order = clause_type.get_props('idx_syntax')
          if not clause_order <= order:
            order = clause_order
          else:
            raise GVizInvalidQuery("Invalid token %s found: " \
                                    "Unexpected clause." % (val,))
          ch = clause_type(self._ctx)     # Consume tokens until the 
                                          # clause is over
          expr._add_handler(ch)
          tkn, val = self._ctx._last
      except StopIteration:             # TODO: Trailing whitespace? (bug ?)
        pass
      if not expr._handlers:            # Something was actually parsed ?
        raise GVizInvalidQuery("No token found: empty string ?")
      return expr
  
  def get_tokens(self, tq):
    try:
      self._ctx = ctx = GVizQLParsingContext()
      self.filters.append(ctx)
      strm = super(GVizQLParser, self).get_tokens(tq)
      ctx.stream = strm
      ctx.parser = self
      for x in strm:
        yield x
    finally:
      self.filters = []
      self._ctx = None
    
class GVizQLParsingContext():
  r"""Used to store global information generated at parsing time. 
  The parser adds the following fields to this object:
    
    - stream : The token stream being processed.
    - parser : The object that's actually parsing the GViz QL expression.
  """
  def __init__(self):
    for attr in 'parser stream'.split():
      setattr(self, attr, None)
    self._last = (None, None)
  
  def filter(self, p, stream):
    r""" Store lookahead token.
    """
    self.parser = p
    self._last = (None, None)
    for t in stream:
      if t[0] is Generic.Error :
        if p.noisy :
          raise GVizInvalidQuery("Invalid token %s " % t[1:])
      elif t[0] is not Whitespace:
        if self._last == (Keyword.Reserved, 'select') and \
            t == (Operator, '*'):
          t = Name.Other, '*'
      elif t[1].endswith('\n'):
        t = (Whitespace, '\n')
      else:
        continue
      self._last = t
      yield t
    
  @property
  def last_token():
    return self._last
  
class GVizQLExpression:
  r"""Compiled GVizQL expression.
  """
  def __init__(self):
    r"""Initialize a compiled GVizQL expression.
    """
    self._handlers = dict()
    self._attrmap = dict()
  def _add_handler(self, ch):
    r"""Add a clause handler to this expression object. Bind the 
    handler's attributes to lazy arguments.
    """
    clause_nm = ch.__class__.get_props('keyw')
    self._handlers[clause_nm] = ch
    for attrnm in ch.__dict__ :
      self._attrmap[attrnm] = clause_nm
    
  def __getattr__(self, attrnm):
    try:
      return getattr(self._handlers[self._attrmap[attrnm]], attrnm)
    except :
      raise AttributeError("'%s' object has no attribute '%s'" % \
                                (self.__class__.__name__, attrnm))
  
  def itereval(self):
    r"""Iterate over the clause handlers present in this expression 
    following evaluation precedence.
    """
    for ct in GVizQLClauseType.itereval():
      ch = self._handlers.get(ct.get_props('keyw'))
      if ch is not None :
        yield ch
  
  def transform(self, schema, data):
    r"""Transform the result set as determined by the GVizQL 
    expression directives and clauses.
    """
    for ch in self.itereval():
      schema, data = ch.transform(schema, data)
    return schema, data

#------------------------------------------------------
#   Helper functions
#------------------------------------------------------

def prepare_ql_data(provider, tq, req, **params):
  r"""Prepare the data and schema to be supplied to an instance of 
  gviz_api.DataTable as determined by a GVizQL expression. This is 
  accomplished by wrapping the original data with multiple iterators.
  
  @param provider   an instance of `IGVizDataProvider` interface 
                    responsible for providing the base result set 
                    (i.e. primary information) subsequently modified 
                    by the application of the GVizQL expression.
  @param tq         the GVizQL expression.
  @param req        an object encapsulating the HTTP request/response 
                    pair.
  @param params     further parameters supported by `provider`.
  @return           a binary tuple. The first item is the schema 
                    describing the column names, data types, and 
                    labels, as well as data structures from where 
                    data will be retrieved. The second is the actual 
                    data resulting from the application of the query 
                    (quite often in the form of iterators).
  """
  sch = provider.get_data_schema.im_func.func_code
  sch_args = (sch.co_argcount > 1) and (req,) or ()
  if not tq:
    data = provider.get_data(req, None, **params)
    return (provider.get_data_schema(*sch_args), data)
  else:
    tq = GVizQLParser().parse(tq)
    data = provider.get_data(req, tq, **params)
    sch = provider.get_data_schema(*sch_args)
    return tq.transform(sch, data)

#------------------------------------------------------
#   Global Testing
#------------------------------------------------------

from testing.test_gvizql import __test__, TEST_DATA_GVIZSCHEMA, \
                            TEST_DATA_GVIZDATA
def test_suite():
  from doctest import ELLIPSIS, NORMALIZE_WHITESPACE, REPORT_UDIFF
  from unittest import defaultTestLoader
  from string import whitespace
  import sys
  
  from api import GVizInvalidQuery
  from testing.dutest import MultiTestLoader, DocTestLoader
  
  def parse(expr, *attrs, **kwds):
    # Test lexical analysis
    print "*****\n* Tokens\n*****"
    newline = False
    p = GVizQLParser()
    p.noisy = False
    for tkn, val in p.get_tokens(expr):
      if tkn is not Whitespace:
        if newline:
          print
        else:
          newline = True
        print tkn, val,
    if not (tkn is Whitespace and val == '\n'):  # Check for EOL token.
      raise AssertionError('Expected : %s , %r \n\nGot : %s , %r' % \
                                  (Whitespace, u'\n', tkn, val))
    if attrs :
      # Test parsing and compilation
      print
      print "*****\n* Parsing\n*****",
      from api import GVizUnsupportedQueryOp
      try:
        expr = p.parse(expr)
      except GVizUnsupportedQueryOp :
        print '\nNotSupported  :(',
      except GVizInvalidQuery, exc :
        print 
        print exc.message
      else:
        for attrnm in attrs :
          print
          print getattr(expr, attrnm),
        # Test evaluation and transformations on result sets
        print
        print "*****\n* Result\n*****",
        try:
          schema, data = expr.transform(TEST_DATA_GVIZSCHEMA, \
                                        TEST_DATA_GVIZDATA)
        except Exception, exc:
          print
          print exc.__class__.__name__, ' : ', exc.message,
        else:
          print
          print "= Columns =",
          if isinstance(schema, dict):
            def iter_schema():
              return ((k,) + v for k, v in schema.iteritems())
          else:
            iter_schema = lambda : schema
          for col in iter_schema() :
            print
            print col[0], col[1],
            try :
              print col[2],
            except IndexError :
              pass
          print 
          for row in data :
            print "= Row ="
            for val, col in izip(row, iter_schema()):
              print '  ', col[0], '=', val
  
  l = MultiTestLoader([defaultTestLoader, \
                        DocTestLoader(
                            extraglobs=dict(parse=parse),
                            optionflags=ELLIPSIS \
                                        | NORMALIZE_WHITESPACE \
                                        | REPORT_UDIFF \
                          )])
  return l.loadTestsFromModule(sys.modules[__name__])
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.