1 # Copyright (C) 2021-2022 Wind River Systems, Inc.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 from sqlalchemy.sql.elements import ColumnElement
16 from sqlalchemy import or_
18 from o2common.helper import o2logging
19 logger = o2logging.get_logger(__name__)
22 def gen_filter(obj: ColumnElement, filter_str: str):
25 filter_without_space = filter_str.replace(" ", "")
26 items = filter_without_space.split(';')
31 i = i.replace("(", "")
33 i = i.replace(")", "")
34 filter_expr = i.split(',')
35 if len(filter_expr) < 3:
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))
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.' %
52 if operation in ['eq', 'neq', 'gt', 'lt', 'gte', 'lte']:
54 raise KeyError('Filter operation one is only support one value.')
55 elif operation in ['in', 'nin', 'cont', 'ncont']:
57 raise KeyError('Filter operation value is needed.')
59 raise KeyError('Filter operation value not support.')
64 if val.lower() == 'null':
66 ll.append(getattr(obj, key) == val)
67 elif operation == 'neq':
69 if val.lower() == 'null':
71 ll.append(getattr(obj, key) != val)
72 elif operation == 'gt':
74 ll.append(getattr(obj, key) > val)
75 elif operation == 'lt':
77 ll.append(getattr(obj, key) < val)
78 elif operation == 'gte':
80 ll.append(getattr(obj, key) >= val)
81 elif operation == 'lte':
83 ll.append(getattr(obj, key) <= val)
84 elif operation == 'in':
85 ll.append(getattr(obj, key).in_(values))
86 elif operation == 'nin':
87 ll.append(~getattr(obj, key).in_(values))
88 elif operation == 'cont':
91 val_list.append(getattr(obj, key).contains(val))
92 ll.append(or_(*val_list))
93 elif operation == 'ncont':
96 val_list.append(getattr(obj, key).contains(val))
97 ll.append(~or_(*val_list))