Fix filter issue to support value with space
[pti/o2.git] / o2common / domain / filter.py
1 # Copyright (C) 2021-2022 Wind River Systems, Inc.
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License");
4 #  you may not use this file except in compliance with the License.
5 #  You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #  Unless required by applicable law or agreed to in writing, software
10 #  distributed under the License is distributed on an "AS IS" BASIS,
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #  See the License for the specific language governing permissions and
13 #  limitations under the License.
14
15 from sqlalchemy.sql.elements import ColumnElement
16 from sqlalchemy import or_
17
18 from o2common.helper import o2logging
19 logger = o2logging.get_logger(__name__)
20
21
22 def gen_orm_filter(obj: ColumnElement, filter_str: str):
23     if not filter_str:
24         return []
25     # filter_without_space = filter_str.replace(" ", "")
26     filter_without_space = filter_str.strip(' ()')
27     items = filter_without_space.split(';')
28
29     filter_list = list()
30     for i in items:
31         # if '(' in i:
32         #     i = i.replace("(", "")
33         # if ')' in i:
34         #     i = i.replace(")", "")
35         filter_expr = i.split(',')
36         if len(filter_expr) < 3:
37             continue
38         filter_op = filter_expr[0].strip()
39         filter_key = filter_expr[1].strip()
40         filter_vals = filter_expr[2:]
41         filter_list.extend(toFilterArgs(
42             filter_op, obj, filter_key, filter_vals))
43     logger.debug('Filter list length: %d' % len(filter_list))
44     return filter_list
45
46
47 def toFilterArgs(operation: str, obj: ColumnElement, key: str, values: list):
48     # if not hasattr(obj, key):
49     #     logger.warning('Filter attrName %s not in Object %s' %
50     #                    (key, str(obj)))
51     #     raise KeyError(
52     #         'Filter attrName {} not in the Object'.format(key))
53
54     # if operation in ['eq', 'neq', 'gt', 'lt', 'gte', 'lte']:
55     #     if len(values) != 1:
56     #         raise KeyError(
57     #             'Filter operation one {} is only support one value'.
58     #             format(operation))
59     # elif operation in ['in', 'nin', 'cont', 'ncont']:
60     #     if len(values) == 0:
61     #         raise KeyError('Filter operation {} value is needed'.
62     #                        format(operation))
63     # else:
64     #     raise KeyError('Filter operation {} not support'.format(operation))
65
66     ll = list()
67     if operation == 'eq':
68         val = values[0]
69         if val.lower() == 'null':
70             val = None
71         ll.append(getattr(obj, key) == val)
72     elif operation == 'neq':
73         val = values[0]
74         if val.lower() == 'null':
75             val = None
76         ll.append(getattr(obj, key) != val)
77     elif operation == 'gt':
78         val = values[0]
79         ll.append(getattr(obj, key) > val)
80     elif operation == 'lt':
81         val = values[0]
82         ll.append(getattr(obj, key) < val)
83     elif operation == 'gte':
84         val = values[0]
85         ll.append(getattr(obj, key) >= val)
86     elif operation == 'lte':
87         val = values[0]
88         ll.append(getattr(obj, key) <= val)
89     elif operation == 'in':
90         ll.append(getattr(obj, key).in_(values))
91     elif operation == 'nin':
92         ll.append(~getattr(obj, key).in_(values))
93     elif operation == 'cont':
94         val_list = list()
95         for val in values:
96             val_list.append(getattr(obj, key).contains(val))
97         ll.append(or_(*val_list))
98     elif operation == 'ncont':
99         val_list = list()
100         for val in values:
101             val_list.append(getattr(obj, key).contains(val))
102         ll.append(~or_(*val_list))
103     return ll