blob: c994640d77d78c082aedd7bfcf14d7c40b266da5 [file] [log] [blame]
tierno87858ca2018-10-08 16:30:15 +02001# -*- coding: utf-8 -*-
2
3# Copyright 2018 Telefonica S.A.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14# implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
tierno5c012612018-04-19 16:01:59 +020018import logging
tierno3054f782018-04-25 16:59:53 +020019from osm_common.dbbase import DbException, DbBase
tierno6472e2b2019-09-02 16:04:16 +000020from osm_common.dbmongo import deep_update
tierno5c012612018-04-19 16:01:59 +020021from http import HTTPStatus
22from uuid import uuid4
23from copy import deepcopy
24
25__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
26
27
28class DbMemory(DbBase):
29
tierno1e9a3292018-11-05 18:18:45 +010030 def __init__(self, logger_name='db', lock=False):
31 super().__init__(logger_name, lock)
tierno5c012612018-04-19 16:01:59 +020032 self.db = {}
33
34 def db_connect(self, config):
tierno87858ca2018-10-08 16:30:15 +020035 """
36 Connect to database
37 :param config: Configuration of database
38 :return: None or raises DbException on error
39 """
tierno5c012612018-04-19 16:01:59 +020040 if "logger_name" in config:
41 self.logger = logging.getLogger(config["logger_name"])
tiernoeef7cb72018-11-12 11:51:49 +010042 master_key = config.get("commonkey") or config.get("masterpassword")
43 if master_key:
44 self.set_secret_key(master_key)
tierno5c012612018-04-19 16:01:59 +020045
46 @staticmethod
tierno87858ca2018-10-08 16:30:15 +020047 def _format_filter(q_filter):
tierno6472e2b2019-09-02 16:04:16 +000048 db_filter = {}
49 # split keys with ANYINDEX in this way:
50 # {"A.B.ANYINDEX.C.D.ANYINDEX.E": v } -> {"A.B.ANYINDEX": {"C.D.ANYINDEX": {"E": v}}}
51 if q_filter:
52 for k, v in q_filter.items():
53 db_v = v
54 kleft, _, kright = k.rpartition(".ANYINDEX.")
55 while kleft:
56 k = kleft + ".ANYINDEX"
57 db_v = {kright: db_v}
58 kleft, _, kright = k.rpartition(".ANYINDEX.")
59 deep_update(db_filter, {k: db_v})
60
61 return db_filter
tierno5c012612018-04-19 16:01:59 +020062
tierno87858ca2018-10-08 16:30:15 +020063 def _find(self, table, q_filter):
tierno6472e2b2019-09-02 16:04:16 +000064
65 def recursive_find(key_list, key_next_index, content, operator, target):
66 if key_next_index == len(key_list) or content is None:
67 try:
68 if operator == "eq":
69 if isinstance(target, list) and not isinstance(content, list):
70 return True if content in target else False
71 return True if content == target else False
72 elif operator in ("neq", "ne"):
73 if isinstance(target, list) and not isinstance(content, list):
74 return True if content not in target else False
75 return True if content != target else False
76 if operator == "gt":
77 return content > target
78 elif operator == "gte":
79 return content >= target
80 elif operator == "lt":
81 return content < target
82 elif operator == "lte":
83 return content <= target
84 elif operator == "cont":
85 return content in target
86 elif operator == "ncont":
87 return content not in target
88 else:
89 raise DbException("Unknown filter operator '{}' in key '{}'".
90 format(operator, ".".join(key_list)), http_code=HTTPStatus.BAD_REQUEST)
91 except TypeError:
92 return False
93
94 elif isinstance(content, dict):
95 return recursive_find(key_list, key_next_index+1, content.get(key_list[key_next_index]), operator,
96 target)
97 elif isinstance(content, list):
98 look_for_match = True # when there is a match return immediately
99 if (target is None and operator not in ("neq", "ne")) or \
100 (target is not None and operator in ("neq", "ne")):
101 look_for_match = False # when there is a match return immediately
102
103 for content_item in content:
104 if key_list[key_next_index] == "ANYINDEX" and isinstance(v, dict):
105 for k2, v2 in target.items():
106 k_new_list = k2.split(".")
107 new_operator = "eq"
108 if k_new_list[-1] in ("eq", "ne", "gt", "gte", "lt", "lte", "cont", "ncont", "neq"):
109 new_operator = k_new_list.pop()
110 if not recursive_find(k_new_list, 0, content_item, new_operator, v2):
111 match = False
112 break
113 else:
114 match = True
115
116 else:
117 match = recursive_find(key_list, key_next_index, content_item, operator, target)
118 if match == look_for_match:
119 return match
120 if key_list[key_next_index].isdecimal() and int(key_list[key_next_index]) < len(content):
121 match = recursive_find(key_list, key_next_index+1, content[int(key_list[key_next_index])],
122 operator, target)
123 if match == look_for_match:
124 return match
125 return not look_for_match
126 else: # content is not dict, nor list neither None, so not found
127 if operator in ("neq", "ne"):
128 return True if target is None else False
129 else:
130 return True if target is None else False
131
tierno5c012612018-04-19 16:01:59 +0200132 for i, row in enumerate(self.db.get(table, ())):
tierno6472e2b2019-09-02 16:04:16 +0000133 q_filter = q_filter or {}
134 for k, v in q_filter.items():
135 k_list = k.split(".")
136 operator = "eq"
137 if k_list[-1] in ("eq", "ne", "gt", "gte", "lt", "lte", "cont", "ncont", "neq"):
138 operator = k_list.pop()
139 match = recursive_find(k_list, 0, row, operator, v)
140 if not match:
141 break
142 else:
143 # match
tierno5c012612018-04-19 16:01:59 +0200144 yield i, row
145
tierno87858ca2018-10-08 16:30:15 +0200146 def get_list(self, table, q_filter=None):
147 """
148 Obtain a list of entries matching q_filter
149 :param table: collection or table
150 :param q_filter: Filter
151 :return: a list (can be empty) with the found entries. Raises DbException on error
152 """
tierno5c012612018-04-19 16:01:59 +0200153 try:
tiernob20a9022018-05-22 12:07:05 +0200154 result = []
tierno1e9a3292018-11-05 18:18:45 +0100155 with self.lock:
156 for _, row in self._find(table, self._format_filter(q_filter)):
157 result.append(deepcopy(row))
tiernob20a9022018-05-22 12:07:05 +0200158 return result
tierno5c012612018-04-19 16:01:59 +0200159 except DbException:
160 raise
161 except Exception as e: # TODO refine
162 raise DbException(str(e))
163
tierno87858ca2018-10-08 16:30:15 +0200164 def get_one(self, table, q_filter=None, fail_on_empty=True, fail_on_more=True):
165 """
166 Obtain one entry matching q_filter
167 :param table: collection or table
168 :param q_filter: Filter
169 :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case
170 it raises a DbException
171 :param fail_on_more: If more than one matches filter it returns one of then unless this flag is set tu True, so
172 that it raises a DbException
173 :return: The requested element, or None
174 """
tierno5c012612018-04-19 16:01:59 +0200175 try:
tiernob20a9022018-05-22 12:07:05 +0200176 result = None
tierno1e9a3292018-11-05 18:18:45 +0100177 with self.lock:
178 for _, row in self._find(table, self._format_filter(q_filter)):
179 if not fail_on_more:
180 return deepcopy(row)
181 if result:
182 raise DbException("Found more than one entry with filter='{}'".format(q_filter),
183 HTTPStatus.CONFLICT.value)
184 result = row
tiernob20a9022018-05-22 12:07:05 +0200185 if not result and fail_on_empty:
tierno87858ca2018-10-08 16:30:15 +0200186 raise DbException("Not found entry with filter='{}'".format(q_filter), HTTPStatus.NOT_FOUND)
tiernob20a9022018-05-22 12:07:05 +0200187 return deepcopy(result)
tierno5c012612018-04-19 16:01:59 +0200188 except Exception as e: # TODO refine
189 raise DbException(str(e))
190
tierno87858ca2018-10-08 16:30:15 +0200191 def del_list(self, table, q_filter=None):
192 """
193 Deletes all entries that match q_filter
194 :param table: collection or table
195 :param q_filter: Filter
196 :return: Dict with the number of entries deleted
197 """
tierno5c012612018-04-19 16:01:59 +0200198 try:
199 id_list = []
tierno1e9a3292018-11-05 18:18:45 +0100200 with self.lock:
201 for i, _ in self._find(table, self._format_filter(q_filter)):
202 id_list.append(i)
tierno5c012612018-04-19 16:01:59 +0200203 deleted = len(id_list)
Eduardo Sousa857731b2018-04-26 15:55:05 +0100204 for i in reversed(id_list):
tierno5c012612018-04-19 16:01:59 +0200205 del self.db[table][i]
206 return {"deleted": deleted}
207 except DbException:
208 raise
209 except Exception as e: # TODO refine
210 raise DbException(str(e))
211
tierno87858ca2018-10-08 16:30:15 +0200212 def del_one(self, table, q_filter=None, fail_on_empty=True):
213 """
214 Deletes one entry that matches q_filter
215 :param table: collection or table
216 :param q_filter: Filter
217 :param fail_on_empty: If nothing matches filter it returns '0' deleted unless this flag is set tu True, in
218 which case it raises a DbException
219 :return: Dict with the number of entries deleted
220 """
tierno5c012612018-04-19 16:01:59 +0200221 try:
tierno1e9a3292018-11-05 18:18:45 +0100222 with self.lock:
223 for i, _ in self._find(table, self._format_filter(q_filter)):
224 break
225 else:
226 if fail_on_empty:
227 raise DbException("Not found entry with filter='{}'".format(q_filter), HTTPStatus.NOT_FOUND)
228 return None
229 del self.db[table][i]
tierno5c012612018-04-19 16:01:59 +0200230 return {"deleted": 1}
231 except Exception as e: # TODO refine
232 raise DbException(str(e))
233
tierno6472e2b2019-09-02 16:04:16 +0000234 def set_one(self, table, q_filter, update_dict, fail_on_empty=True, unset=None, pull=None, push=None):
235 """
236 Modifies an entry at database
237 :param table: collection or table
238 :param q_filter: Filter
239 :param update_dict: Plain dictionary with the content to be updated. It is a dot separated keys and a value
240 :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case
241 it raises a DbException
242 :param unset: Plain dictionary with the content to be removed if exist. It is a dot separated keys, value is
243 ignored. If not exist, it is ignored
244 :param pull: Plain dictionary with the content to be removed from an array. It is a dot separated keys and value
245 if exist in the array is removed. If not exist, it is ignored
246 :param push: Plain dictionary with the content to be appended to an array. It is a dot separated keys and value
247 is appended to the end of the array
248 :return: Dict with the number of entries modified. None if no matching is found.
249 """
250 try:
251 with self.lock:
252 for i, db_item in self._find(table, self._format_filter(q_filter)):
253 break
254 else:
255 if fail_on_empty:
256 raise DbException("Not found entry with _id='{}'".format(q_filter), HTTPStatus.NOT_FOUND)
257 return None
258 for k, v in update_dict.items():
259 db_nested = db_item
260 k_list = k.split(".")
261 k_nested_prev = k_list[0]
262 for k_nested in k_list[1:]:
263 if isinstance(db_nested[k_nested_prev], dict):
264 if k_nested not in db_nested[k_nested_prev]:
265 db_nested[k_nested_prev][k_nested] = None
266 elif isinstance(db_nested[k_nested_prev], list) and k_nested.isdigit():
267 # extend list with Nones if index greater than list
268 k_nested = int(k_nested)
269 if k_nested >= len(db_nested[k_nested_prev]):
270 db_nested[k_nested_prev] += [None] * (k_nested - len(db_nested[k_nested_prev]) + 1)
271 elif db_nested[k_nested_prev] is None:
272 db_nested[k_nested_prev] = {k_nested: None}
273 else: # number, string, boolean, ... or list but with not integer key
274 raise DbException("Cannot set '{}' on existing '{}={}'".format(k, k_nested_prev,
275 db_nested[k_nested_prev]))
276
277 db_nested = db_nested[k_nested_prev]
278 k_nested_prev = k_nested
279
280 db_nested[k_nested_prev] = v
281 return {"updated": 1}
282 except DbException:
283 raise
284 except Exception as e: # TODO refine
285 raise DbException(str(e))
286
tierno87858ca2018-10-08 16:30:15 +0200287 def replace(self, table, _id, indata, fail_on_empty=True):
288 """
289 Replace the content of an entry
290 :param table: collection or table
291 :param _id: internal database id
292 :param indata: content to replace
293 :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case
294 it raises a DbException
295 :return: Dict with the number of entries replaced
296 """
tierno5c012612018-04-19 16:01:59 +0200297 try:
tierno1e9a3292018-11-05 18:18:45 +0100298 with self.lock:
299 for i, _ in self._find(table, self._format_filter({"_id": _id})):
300 break
301 else:
302 if fail_on_empty:
303 raise DbException("Not found entry with _id='{}'".format(_id), HTTPStatus.NOT_FOUND)
304 return None
305 self.db[table][i] = deepcopy(indata)
Eduardo Sousa22f0fcd2018-04-26 15:43:28 +0100306 return {"updated": 1}
tierno136f2952018-10-19 13:01:03 +0200307 except DbException:
308 raise
tierno5c012612018-04-19 16:01:59 +0200309 except Exception as e: # TODO refine
310 raise DbException(str(e))
311
312 def create(self, table, indata):
tierno87858ca2018-10-08 16:30:15 +0200313 """
314 Add a new entry at database
315 :param table: collection or table
316 :param indata: content to be added
317 :return: database id of the inserted element. Raises a DbException on error
318 """
tierno5c012612018-04-19 16:01:59 +0200319 try:
320 id = indata.get("_id")
321 if not id:
322 id = str(uuid4())
323 indata["_id"] = id
tierno1e9a3292018-11-05 18:18:45 +0100324 with self.lock:
325 if table not in self.db:
326 self.db[table] = []
327 self.db[table].append(deepcopy(indata))
tierno5c012612018-04-19 16:01:59 +0200328 return id
329 except Exception as e: # TODO refine
330 raise DbException(str(e))
331
tierno6472e2b2019-09-02 16:04:16 +0000332 def create_list(self, table, indata_list):
333 """
334 Add a new entry at database
335 :param table: collection or table
336 :param indata_list: list content to be added
337 :return: database ids of the inserted element. Raises a DbException on error
338 """
339 try:
340 _ids = []
341 for indata in indata_list:
342 _id = indata.get("_id")
343 if not _id:
344 _id = str(uuid4())
345 indata["_id"] = _id
346 with self.lock:
347 if table not in self.db:
348 self.db[table] = []
349 self.db[table].append(deepcopy(indata))
350 _ids.append(_id)
351 return _ids
352 except Exception as e: # TODO refine
353 raise DbException(str(e))
354
tierno5c012612018-04-19 16:01:59 +0200355
356if __name__ == '__main__':
357 # some test code
tierno3054f782018-04-25 16:59:53 +0200358 db = DbMemory()
tierno5c012612018-04-19 16:01:59 +0200359 db.create("test", {"_id": 1, "data": 1})
360 db.create("test", {"_id": 2, "data": 2})
361 db.create("test", {"_id": 3, "data": 3})
362 print("must be 3 items:", db.get_list("test"))
363 print("must return item 2:", db.get_list("test", {"_id": 2}))
364 db.del_one("test", {"_id": 2})
365 print("must be emtpy:", db.get_list("test", {"_id": 2}))