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