Home | History | Annotate | Download | only in tko
      1 """
      2 This library provides a bunch of miscellaneous parameter parsing,
      3 sql generating and list cleanup library functions that are used
      4 by both the reporting cli and web interface.
      5 """
      6 
      7 import os
      8 import re
      9 import sys
     10 
     11 import common
     12 from autotest_lib.tko import display
     13 from autotest_lib.tko import frontend
     14 
     15 def parse_scrub_and_gen_condition(condition, valid_field_dict):
     16     me = parse_scrub_and_gen_condition   # shorten the name
     17     compare_ops = {'=':'=', '<>':'<>', '==':'=', '!=':'<>', '>':'>',
     18                    '<':'<', '>=':'>=', '<=':'<=', '~':'LIKE', '#':'REGEXP'}
     19 
     20     # strip white space
     21     condition = condition.strip()
     22 
     23     # OR
     24     match = re.match(r'^(.+)[|](.+)$', condition)
     25     if match:
     26         (a_sql, a_values) = me(match.group(1), valid_field_dict)
     27         (b_sql, b_values) = me(match.group(2), valid_field_dict)
     28         return (" (%s) OR (%s) " % (a_sql, b_sql),
     29                 a_values + b_values)
     30 
     31     # AND
     32     match = re.match(r'^(.+)[&](.+)$', condition)
     33     if match:
     34         (a_sql, a_values) = me(match.group(1), valid_field_dict)
     35         (b_sql, b_values) = me(match.group(2), valid_field_dict)
     36         return (" (%s) AND (%s) " % (a_sql, b_sql),
     37                 a_values + b_values)
     38 
     39     # '<field> <op> <value>' where value can be quoted
     40     # double quotes are escaped....i.e.  '''' is the same as "'"
     41     regex = r'^(%s)[ \t]*(%s)[ \t]*' + \
     42             r'(\'((\'\'|[^\'])*)\'|"((""|[^"])*)"|([^\'"].*))$'
     43     regex = regex % ('|'.join(valid_field_dict.keys()),
     44                      '|'.join(compare_ops.keys()))
     45     match = re.match(regex, condition)
     46     if match:
     47         field = valid_field_dict[match.group(1)]
     48         op = compare_ops[match.group(2)]
     49         if match.group(5):
     50             val = match.group(4).replace("''", "'")
     51         elif match.group(7):
     52             val = match.group(6).replace('""', '"')
     53         elif match.group(8):
     54             val = match.group(8)
     55         else:
     56             raise "Internal error"
     57         return ("%s %s %%s" % (field, op), [val])
     58 
     59     raise "Could not parse '%s' (%s)" % (condition, regex)
     60