80fe322c46a6159f35bda8c276133590eab430fa
[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     items = filter_without_space.split(';')
27
28     filter_list = list()
29     for i in items:
30         if '(' in i:
31             i = i.replace("(", "")
32         if ')' in i:
33             i = i.replace(")", "")
34         filter_expr = i.split(',')
35         if len(filter_expr) < 3:
36             continue
37         filter_op = filter_expr[0]
38         filter_key = filter_expr[1]
39         filter_vals = filter_expr[2:]
40         filter_list.extend(toFilterArgs(
41             filter_op, obj, filter_key, filter_vals))
42     logger.info('Filter list length: %d' % len(filter_list))
43     return filter_list
44
45
46 def toFilterArgs(operation: str, obj: ColumnElement, key: str, values: list):
47     if not hasattr(obj, key):
48         logger.warning('Filter attrName %s not in Object %s.' %
49                        (key, str(obj)))
50         raise KeyError(
51             'Filter attrName {} not in the Object'.format(key))
52
53     if operation in ['eq', 'neq', 'gt', 'lt', 'gte', 'lte']:
54         if len(values) != 1:
55             raise KeyError(
56                 'Filter operation one {} is only support one value.'.
57                 format(operation))
58     elif operation in ['in', 'nin', 'cont', 'ncont']:
59         if len(values) == 0:
60             raise KeyError('Filter operation {} value is needed.'.
61                            format(operation))
62     else:
63         raise KeyError('Filter operation {} not support.'.format(operation))
64
65     ll = list()
66     if operation == 'eq':
67         val = values[0]
68         if val.lower() == 'null':
69             val = None
70         ll.append(getattr(obj, key) == val)
71     elif operation == 'neq':
72         val = values[0]
73         if val.lower() == 'null':
74             val = None
75         ll.append(getattr(obj, key) != val)
76     elif operation == 'gt':
77         val = values[0]
78         ll.append(getattr(obj, key) > val)
79     elif operation == 'lt':
80         val = values[0]
81         ll.append(getattr(obj, key) < val)
82     elif operation == 'gte':
83         val = values[0]
84         ll.append(getattr(obj, key) >= val)
85     elif operation == 'lte':
86         val = values[0]
87         ll.append(getattr(obj, key) <= val)
88     elif operation == 'in':
89         ll.append(getattr(obj, key).in_(values))
90     elif operation == 'nin':
91         ll.append(~getattr(obj, key).in_(values))
92     elif operation == 'cont':
93         val_list = list()
94         for val in values:
95             val_list.append(getattr(obj, key).contains(val))
96         ll.append(or_(*val_list))
97     elif operation == 'ncont':
98         val_list = list()
99         for val in values:
100             val_list.append(getattr(obj, key).contains(val))
101         ll.append(~or_(*val_list))
102     return ll