X-Git-Url: https://osm.etsi.org/gitweb/?a=blobdiff_plain;f=osm_common%2Fdbmemory.py;h=1b6d7ac2689870e1abd77f13fd5028831d3579df;hb=refs%2Fchanges%2F80%2F8380%2F3;hp=c2d9a113273a03566c2c8f5b476aba2eb68909ef;hpb=eef7cb7a4f704bf0d29e6d8ece5195dc3faabb69;p=osm%2Fcommon.git diff --git a/osm_common/dbmemory.py b/osm_common/dbmemory.py index c2d9a11..1b6d7ac 100644 --- a/osm_common/dbmemory.py +++ b/osm_common/dbmemory.py @@ -17,6 +17,7 @@ import logging from osm_common.dbbase import DbException, DbBase +from osm_common.dbmongo import deep_update from http import HTTPStatus from uuid import uuid4 from copy import deepcopy @@ -44,16 +45,106 @@ class DbMemory(DbBase): @staticmethod def _format_filter(q_filter): - return q_filter # TODO + db_filter = {} + # split keys with ANYINDEX in this way: + # {"A.B.ANYINDEX.C.D.ANYINDEX.E": v } -> {"A.B.ANYINDEX": {"C.D.ANYINDEX": {"E": v}}} + if q_filter: + for k, v in q_filter.items(): + db_v = v + kleft, _, kright = k.rpartition(".ANYINDEX.") + while kleft: + k = kleft + ".ANYINDEX" + db_v = {kright: db_v} + kleft, _, kright = k.rpartition(".ANYINDEX.") + deep_update(db_filter, {k: db_v}) + + return db_filter def _find(self, table, q_filter): + + def recursive_find(key_list, key_next_index, content, oper, target): + if key_next_index == len(key_list) or content is None: + try: + if oper in ("eq", "cont"): + if isinstance(target, list): + if isinstance(content, list): + return any(content_item in target for content_item in content) + return content in target + elif isinstance(content, list): + return target in content + else: + return content == target + elif oper in ("neq", "ne", "ncont"): + if isinstance(target, list): + if isinstance(content, list): + return all(content_item not in target for content_item in content) + return content not in target + elif isinstance(content, list): + return target not in content + else: + return content != target + if oper == "gt": + return content > target + elif oper == "gte": + return content >= target + elif oper == "lt": + return content < target + elif oper == "lte": + return content <= target + else: + raise DbException("Unknown filter operator '{}' in key '{}'". + format(oper, ".".join(key_list)), http_code=HTTPStatus.BAD_REQUEST) + except TypeError: + return False + + elif isinstance(content, dict): + return recursive_find(key_list, key_next_index + 1, content.get(key_list[key_next_index]), oper, + target) + elif isinstance(content, list): + look_for_match = True # when there is a match return immediately + if (target is None) != (oper in ("neq", "ne", "ncont")): # one True and other False (Xor) + look_for_match = False # when there is not a match return immediately + + for content_item in content: + if key_list[key_next_index] == "ANYINDEX" and isinstance(v, dict): + matches = True + for k2, v2 in target.items(): + k_new_list = k2.split(".") + new_operator = "eq" + if k_new_list[-1] in ("eq", "ne", "gt", "gte", "lt", "lte", "cont", "ncont", "neq"): + new_operator = k_new_list.pop() + if not recursive_find(k_new_list, 0, content_item, new_operator, v2): + matches = False + break + + else: + matches = recursive_find(key_list, key_next_index, content_item, oper, target) + if matches == look_for_match: + return matches + if key_list[key_next_index].isdecimal() and int(key_list[key_next_index]) < len(content): + matches = recursive_find(key_list, key_next_index + 1, content[int(key_list[key_next_index])], + oper, target) + if matches == look_for_match: + return matches + return not look_for_match + else: # content is not dict, nor list neither None, so not found + if oper in ("neq", "ne", "ncont"): + return target is not None + else: + return target is None + for i, row in enumerate(self.db.get(table, ())): - match = True - if q_filter: - for k, v in q_filter.items(): - if k not in row or v != row[k]: - match = False - if match: + q_filter = q_filter or {} + for k, v in q_filter.items(): + k_list = k.split(".") + operator = "eq" + if k_list[-1] in ("eq", "ne", "gt", "gte", "lt", "lte", "cont", "ncont", "neq"): + operator = k_list.pop() + matches = recursive_find(k_list, 0, row, operator, v) + if not matches: + break + else: + # match yield i, row def get_list(self, table, q_filter=None): @@ -74,6 +165,22 @@ class DbMemory(DbBase): except Exception as e: # TODO refine raise DbException(str(e)) + def count(self, table, q_filter=None): + """ + Count the number of entries matching q_filter + :param table: collection or table + :param q_filter: Filter + :return: number of entries found (can be zero) + :raise: DbException on error + """ + try: + with self.lock: + return sum(1 for x in self._find(table, self._format_filter(q_filter))) + except DbException: + raise + except Exception as e: # TODO refine + raise DbException(str(e)) + def get_one(self, table, q_filter=None, fail_on_empty=True, fail_on_more=True): """ Obtain one entry matching q_filter @@ -144,6 +251,59 @@ class DbMemory(DbBase): except Exception as e: # TODO refine raise DbException(str(e)) + def set_one(self, table, q_filter, update_dict, fail_on_empty=True, unset=None, pull=None, push=None): + """ + Modifies an entry at database + :param table: collection or table + :param q_filter: Filter + :param update_dict: Plain dictionary with the content to be updated. It is a dot separated keys and a value + :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case + it raises a DbException + :param unset: Plain dictionary with the content to be removed if exist. It is a dot separated keys, value is + ignored. If not exist, it is ignored + :param pull: Plain dictionary with the content to be removed from an array. It is a dot separated keys and value + if exist in the array is removed. If not exist, it is ignored + :param push: Plain dictionary with the content to be appended to an array. It is a dot separated keys and value + is appended to the end of the array + :return: Dict with the number of entries modified. None if no matching is found. + """ + try: + with self.lock: + for i, db_item in self._find(table, self._format_filter(q_filter)): + break + else: + if fail_on_empty: + raise DbException("Not found entry with _id='{}'".format(q_filter), HTTPStatus.NOT_FOUND) + return None + for k, v in update_dict.items(): + db_nested = db_item + k_list = k.split(".") + k_item_prev = k_list[0] + for k_item in k_list[1:]: + if isinstance(db_nested[k_item_prev], dict): + if k_item not in db_nested[k_item_prev]: + db_nested[k_item_prev][k_item] = None + elif isinstance(db_nested[k_item_prev], list) and k_item.isdigit(): + # extend list with Nones if index greater than list + k_item = int(k_item) + if k_item >= len(db_nested[k_item_prev]): + db_nested[k_item_prev] += [None] * (k_item - len(db_nested[k_item_prev]) + 1) + elif db_nested[k_item_prev] is None: + db_nested[k_item_prev] = {k_item: None} + else: # number, string, boolean, ... or list but with not integer key + raise DbException("Cannot set '{}' on existing '{}={}'".format(k, k_item_prev, + db_nested[k_item_prev])) + + db_nested = db_nested[k_item_prev] + k_item_prev = k_item + + db_nested[k_item_prev] = v + return {"updated": 1} + except DbException: + raise + except Exception as e: # TODO refine + raise DbException(str(e)) + def replace(self, table, _id, indata, fail_on_empty=True): """ Replace the content of an entry @@ -189,6 +349,30 @@ class DbMemory(DbBase): except Exception as e: # TODO refine raise DbException(str(e)) + def create_list(self, table, indata_list): + """ + Add a new entry at database + :param table: collection or table + :param indata_list: list content to be added + :return: database ids of the inserted element. Raises a DbException on error + """ + try: + _ids = [] + with self.lock: + for indata in indata_list: + _id = indata.get("_id") + if not _id: + _id = str(uuid4()) + indata["_id"] = _id + with self.lock: + if table not in self.db: + self.db[table] = [] + self.db[table].append(deepcopy(indata)) + _ids.append(_id) + return _ids + except Exception as e: # TODO refine + raise DbException(str(e)) + if __name__ == '__main__': # some test code