blob: bae68e2b14a15ef42e287b0b12b3d7cb6693d09b [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
tierno5c012612018-04-19 16:01:59 +020020from http import HTTPStatus
21from uuid import uuid4
22from copy import deepcopy
23
24__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
25
26
27class DbMemory(DbBase):
28
tiernocfc52722018-10-23 11:41:49 +020029 def __init__(self, logger_name='db'):
30 super().__init__(logger_name)
tierno5c012612018-04-19 16:01:59 +020031 self.db = {}
32
33 def db_connect(self, config):
tierno87858ca2018-10-08 16:30:15 +020034 """
35 Connect to database
36 :param config: Configuration of database
37 :return: None or raises DbException on error
38 """
tierno5c012612018-04-19 16:01:59 +020039 if "logger_name" in config:
40 self.logger = logging.getLogger(config["logger_name"])
tiernocfc52722018-10-23 11:41:49 +020041 self.master_password = config.get("masterpassword")
tierno5c012612018-04-19 16:01:59 +020042
43 @staticmethod
tierno87858ca2018-10-08 16:30:15 +020044 def _format_filter(q_filter):
45 return q_filter # TODO
tierno5c012612018-04-19 16:01:59 +020046
tierno87858ca2018-10-08 16:30:15 +020047 def _find(self, table, q_filter):
tierno5c012612018-04-19 16:01:59 +020048 for i, row in enumerate(self.db.get(table, ())):
49 match = True
tierno87858ca2018-10-08 16:30:15 +020050 if q_filter:
51 for k, v in q_filter.items():
tierno5c012612018-04-19 16:01:59 +020052 if k not in row or v != row[k]:
53 match = False
54 if match:
55 yield i, row
56
tierno87858ca2018-10-08 16:30:15 +020057 def get_list(self, table, q_filter=None):
58 """
59 Obtain a list of entries matching q_filter
60 :param table: collection or table
61 :param q_filter: Filter
62 :return: a list (can be empty) with the found entries. Raises DbException on error
63 """
tierno5c012612018-04-19 16:01:59 +020064 try:
tiernob20a9022018-05-22 12:07:05 +020065 result = []
tierno87858ca2018-10-08 16:30:15 +020066 for _, row in self._find(table, self._format_filter(q_filter)):
tiernob20a9022018-05-22 12:07:05 +020067 result.append(deepcopy(row))
68 return result
tierno5c012612018-04-19 16:01:59 +020069 except DbException:
70 raise
71 except Exception as e: # TODO refine
72 raise DbException(str(e))
73
tierno87858ca2018-10-08 16:30:15 +020074 def get_one(self, table, q_filter=None, fail_on_empty=True, fail_on_more=True):
75 """
76 Obtain one entry matching q_filter
77 :param table: collection or table
78 :param q_filter: Filter
79 :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case
80 it raises a DbException
81 :param fail_on_more: If more than one matches filter it returns one of then unless this flag is set tu True, so
82 that it raises a DbException
83 :return: The requested element, or None
84 """
tierno5c012612018-04-19 16:01:59 +020085 try:
tiernob20a9022018-05-22 12:07:05 +020086 result = None
tierno87858ca2018-10-08 16:30:15 +020087 for _, row in self._find(table, self._format_filter(q_filter)):
tierno5c012612018-04-19 16:01:59 +020088 if not fail_on_more:
89 return deepcopy(row)
tiernob20a9022018-05-22 12:07:05 +020090 if result:
tierno87858ca2018-10-08 16:30:15 +020091 raise DbException("Found more than one entry with filter='{}'".format(q_filter),
tierno5c012612018-04-19 16:01:59 +020092 HTTPStatus.CONFLICT.value)
tiernob20a9022018-05-22 12:07:05 +020093 result = row
94 if not result and fail_on_empty:
tierno87858ca2018-10-08 16:30:15 +020095 raise DbException("Not found entry with filter='{}'".format(q_filter), HTTPStatus.NOT_FOUND)
tiernob20a9022018-05-22 12:07:05 +020096 return deepcopy(result)
tierno5c012612018-04-19 16:01:59 +020097 except Exception as e: # TODO refine
98 raise DbException(str(e))
99
tierno87858ca2018-10-08 16:30:15 +0200100 def del_list(self, table, q_filter=None):
101 """
102 Deletes all entries that match q_filter
103 :param table: collection or table
104 :param q_filter: Filter
105 :return: Dict with the number of entries deleted
106 """
tierno5c012612018-04-19 16:01:59 +0200107 try:
108 id_list = []
tierno87858ca2018-10-08 16:30:15 +0200109 for i, _ in self._find(table, self._format_filter(q_filter)):
tierno5c012612018-04-19 16:01:59 +0200110 id_list.append(i)
111 deleted = len(id_list)
Eduardo Sousa857731b2018-04-26 15:55:05 +0100112 for i in reversed(id_list):
tierno5c012612018-04-19 16:01:59 +0200113 del self.db[table][i]
114 return {"deleted": deleted}
115 except DbException:
116 raise
117 except Exception as e: # TODO refine
118 raise DbException(str(e))
119
tierno87858ca2018-10-08 16:30:15 +0200120 def del_one(self, table, q_filter=None, fail_on_empty=True):
121 """
122 Deletes one entry that matches q_filter
123 :param table: collection or table
124 :param q_filter: Filter
125 :param fail_on_empty: If nothing matches filter it returns '0' deleted unless this flag is set tu True, in
126 which case it raises a DbException
127 :return: Dict with the number of entries deleted
128 """
tierno5c012612018-04-19 16:01:59 +0200129 try:
tierno87858ca2018-10-08 16:30:15 +0200130 for i, _ in self._find(table, self._format_filter(q_filter)):
tierno5c012612018-04-19 16:01:59 +0200131 break
132 else:
133 if fail_on_empty:
tierno87858ca2018-10-08 16:30:15 +0200134 raise DbException("Not found entry with filter='{}'".format(q_filter), HTTPStatus.NOT_FOUND)
tierno5c012612018-04-19 16:01:59 +0200135 return None
136 del self.db[table][i]
137 return {"deleted": 1}
138 except Exception as e: # TODO refine
139 raise DbException(str(e))
140
tierno87858ca2018-10-08 16:30:15 +0200141 def replace(self, table, _id, indata, fail_on_empty=True):
142 """
143 Replace the content of an entry
144 :param table: collection or table
145 :param _id: internal database id
146 :param indata: content to replace
147 :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case
148 it raises a DbException
149 :return: Dict with the number of entries replaced
150 """
tierno5c012612018-04-19 16:01:59 +0200151 try:
tierno87858ca2018-10-08 16:30:15 +0200152 for i, _ in self._find(table, self._format_filter({"_id": _id})):
tierno5c012612018-04-19 16:01:59 +0200153 break
154 else:
155 if fail_on_empty:
tierno87858ca2018-10-08 16:30:15 +0200156 raise DbException("Not found entry with _id='{}'".format(_id), HTTPStatus.NOT_FOUND)
tierno5c012612018-04-19 16:01:59 +0200157 return None
158 self.db[table][i] = deepcopy(indata)
Eduardo Sousa22f0fcd2018-04-26 15:43:28 +0100159 return {"updated": 1}
tierno136f2952018-10-19 13:01:03 +0200160 except DbException:
161 raise
tierno5c012612018-04-19 16:01:59 +0200162 except Exception as e: # TODO refine
163 raise DbException(str(e))
164
165 def create(self, table, indata):
tierno87858ca2018-10-08 16:30:15 +0200166 """
167 Add a new entry at database
168 :param table: collection or table
169 :param indata: content to be added
170 :return: database id of the inserted element. Raises a DbException on error
171 """
tierno5c012612018-04-19 16:01:59 +0200172 try:
173 id = indata.get("_id")
174 if not id:
175 id = str(uuid4())
176 indata["_id"] = id
177 if table not in self.db:
178 self.db[table] = []
179 self.db[table].append(deepcopy(indata))
180 return id
181 except Exception as e: # TODO refine
182 raise DbException(str(e))
183
184
185if __name__ == '__main__':
186 # some test code
tierno3054f782018-04-25 16:59:53 +0200187 db = DbMemory()
tierno5c012612018-04-19 16:01:59 +0200188 db.create("test", {"_id": 1, "data": 1})
189 db.create("test", {"_id": 2, "data": 2})
190 db.create("test", {"_id": 3, "data": 3})
191 print("must be 3 items:", db.get_list("test"))
192 print("must return item 2:", db.get_list("test", {"_id": 2}))
193 db.del_one("test", {"_id": 2})
194 print("must be emtpy:", db.get_list("test", {"_id": 2}))