| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 1 | # -*- 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 | |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 18 | import yaml |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 19 | import logging |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 20 | from http import HTTPStatus |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 21 | from copy import deepcopy |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 22 | from Crypto.Cipher import AES |
| 23 | from base64 import b64decode, b64encode |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 24 | from osm_common.common_utils import FakeLock |
| 25 | from threading import Lock |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 26 | |
| 27 | __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>" |
| 28 | |
| 29 | |
| 30 | class DbException(Exception): |
| 31 | |
| 32 | def __init__(self, message, http_code=HTTPStatus.NOT_FOUND): |
| 33 | self.http_code = http_code |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 34 | Exception.__init__(self, "database exception " + str(message)) |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 35 | |
| 36 | |
| 37 | class DbBase(object): |
| 38 | |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 39 | def __init__(self, logger_name='db', lock=False): |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 40 | """ |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 41 | Constructor of dbBase |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 42 | :param logger_name: logging name |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 43 | :param lock: Used to protect simultaneous access to the same instance class by several threads: |
| 44 | False, None: Do not protect, this object will only be accessed by one thread |
| 45 | True: This object needs to be protected by several threads accessing. |
| 46 | Lock object. Use thi Lock for the threads access protection |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 47 | """ |
| 48 | self.logger = logging.getLogger(logger_name) |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 49 | self.secret_key = None # 32 bytes length array used for encrypt/decrypt |
| tierno | 1e9a329 | 2018-11-05 18:18:45 +0100 | [diff] [blame] | 50 | if not lock: |
| 51 | self.lock = FakeLock() |
| 52 | elif lock is True: |
| 53 | self.lock = Lock() |
| 54 | elif isinstance(lock, Lock): |
| 55 | self.lock = lock |
| 56 | else: |
| 57 | raise ValueError("lock parameter must be a Lock classclass or boolean") |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 58 | |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 59 | def db_connect(self, config, target_version=None): |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 60 | """ |
| 61 | Connect to database |
| tierno | cfc5272 | 2018-10-23 11:41:49 +0200 | [diff] [blame] | 62 | :param config: Configuration of database. Contains among others: |
| 63 | host: database hosst (mandatory) |
| 64 | port: database port (mandatory) |
| 65 | name: database name (mandatory) |
| 66 | user: database username |
| 67 | password: database password |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 68 | commonkey: common OSM key used for sensible information encryption |
| 69 | materpassword: same as commonkey, for backward compatibility. Deprecated, to be removed in the future |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 70 | :param target_version: if provided it checks if database contains required version, raising exception otherwise. |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 71 | :return: None or raises DbException on error |
| 72 | """ |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 73 | raise DbException("Method 'db_connect' not implemented") |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 74 | |
| 75 | def db_disconnect(self): |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 76 | """ |
| 77 | Disconnect from database |
| 78 | :return: None |
| 79 | """ |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 80 | pass |
| 81 | |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 82 | def get_list(self, table, q_filter=None): |
| 83 | """ |
| 84 | Obtain a list of entries matching q_filter |
| 85 | :param table: collection or table |
| 86 | :param q_filter: Filter |
| 87 | :return: a list (can be empty) with the found entries. Raises DbException on error |
| 88 | """ |
| tierno | ebbf353 | 2018-05-03 17:49:37 +0200 | [diff] [blame] | 89 | raise DbException("Method 'get_list' not implemented") |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 90 | |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 91 | def get_one(self, table, q_filter=None, fail_on_empty=True, fail_on_more=True): |
| 92 | """ |
| 93 | Obtain one entry matching q_filter |
| 94 | :param table: collection or table |
| 95 | :param q_filter: Filter |
| 96 | :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case |
| 97 | it raises a DbException |
| 98 | :param fail_on_more: If more than one matches filter it returns one of then unless this flag is set tu True, so |
| 99 | that it raises a DbException |
| 100 | :return: The requested element, or None |
| 101 | """ |
| tierno | ebbf353 | 2018-05-03 17:49:37 +0200 | [diff] [blame] | 102 | raise DbException("Method 'get_one' not implemented") |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 103 | |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 104 | def del_list(self, table, q_filter=None): |
| 105 | """ |
| 106 | Deletes all entries that match q_filter |
| 107 | :param table: collection or table |
| 108 | :param q_filter: Filter |
| 109 | :return: Dict with the number of entries deleted |
| 110 | """ |
| tierno | ebbf353 | 2018-05-03 17:49:37 +0200 | [diff] [blame] | 111 | raise DbException("Method 'del_list' not implemented") |
| tierno | 5c01261 | 2018-04-19 16:01:59 +0200 | [diff] [blame] | 112 | |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 113 | def del_one(self, table, q_filter=None, fail_on_empty=True): |
| 114 | """ |
| 115 | Deletes one entry that matches q_filter |
| 116 | :param table: collection or table |
| 117 | :param q_filter: Filter |
| 118 | :param fail_on_empty: If nothing matches filter it returns '0' deleted unless this flag is set tu True, in |
| 119 | which case it raises a DbException |
| 120 | :return: Dict with the number of entries deleted |
| 121 | """ |
| tierno | ebbf353 | 2018-05-03 17:49:37 +0200 | [diff] [blame] | 122 | raise DbException("Method 'del_one' not implemented") |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 123 | |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 124 | def create(self, table, indata): |
| 125 | """ |
| 126 | Add a new entry at database |
| 127 | :param table: collection or table |
| 128 | :param indata: content to be added |
| 129 | :return: database id of the inserted element. Raises a DbException on error |
| 130 | """ |
| 131 | raise DbException("Method 'create' not implemented") |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 132 | |
| tierno | d63ea27 | 2018-11-27 12:03:36 +0100 | [diff] [blame] | 133 | def set_one(self, table, q_filter, update_dict, fail_on_empty=True, unset=None, pull=None, push=None): |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 134 | """ |
| 135 | Modifies an entry at database |
| 136 | :param table: collection or table |
| 137 | :param q_filter: Filter |
| 138 | :param update_dict: Plain dictionary with the content to be updated. It is a dot separated keys and a value |
| 139 | :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case |
| 140 | it raises a DbException |
| tierno | d63ea27 | 2018-11-27 12:03:36 +0100 | [diff] [blame] | 141 | :param unset: Plain dictionary with the content to be removed if exist. It is a dot separated keys, value is |
| 142 | ignored. If not exist, it is ignored |
| 143 | :param pull: Plain dictionary with the content to be removed from an array. It is a dot separated keys and value |
| 144 | if exist in the array is removed. If not exist, it is ignored |
| 145 | :param push: Plain dictionary with the content to be appended to an array. It is a dot separated keys and value |
| 146 | is appended to the end of the array |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 147 | :return: Dict with the number of entries modified. None if no matching is found. |
| 148 | """ |
| 149 | raise DbException("Method 'set_one' not implemented") |
| 150 | |
| 151 | def set_list(self, table, q_filter, update_dict): |
| 152 | """ |
| 153 | Modifies al matching entries at database |
| 154 | :param table: collection or table |
| 155 | :param q_filter: Filter |
| 156 | :param update_dict: Plain dictionary with the content to be updated. It is a dot separated keys and a value |
| 157 | :return: Dict with the number of entries modified |
| 158 | """ |
| 159 | raise DbException("Method 'set_list' not implemented") |
| 160 | |
| 161 | def replace(self, table, _id, indata, fail_on_empty=True): |
| 162 | """ |
| 163 | Replace the content of an entry |
| 164 | :param table: collection or table |
| 165 | :param _id: internal database id |
| 166 | :param indata: content to replace |
| 167 | :param fail_on_empty: If nothing matches filter it returns None unless this flag is set tu True, in which case |
| 168 | it raises a DbException |
| 169 | :return: Dict with the number of entries replaced |
| 170 | """ |
| 171 | raise DbException("Method 'replace' not implemented") |
| 172 | |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 173 | def _join_secret_key(self, update_key): |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 174 | """ |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 175 | Returns a xor byte combination of the internal secret_key and the provided update_key. |
| 176 | It does not modify the internal secret_key. Used for adding salt, join keys, etc. |
| 177 | :param update_key: Can be a string, byte or None. Recommended a long one (e.g. 32 byte length) |
| 178 | :return: joined key in bytes with a 32 bytes length. Can be None if both internal secret_key and update_key |
| 179 | are None |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 180 | """ |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 181 | if not update_key: |
| 182 | return self.secret_key |
| 183 | elif isinstance(update_key, str): |
| 184 | update_key_bytes = update_key.encode() |
| 185 | else: |
| 186 | update_key_bytes = update_key |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 187 | |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 188 | new_secret_key = bytearray(self.secret_key) if self.secret_key else bytearray(32) |
| 189 | for i, b in enumerate(update_key_bytes): |
| 190 | new_secret_key[i % 32] ^= b |
| 191 | return bytes(new_secret_key) |
| 192 | |
| 193 | def set_secret_key(self, new_secret_key, replace=False): |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 194 | """ |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 195 | Updates internal secret_key used for encryption, with a byte xor |
| 196 | :param new_secret_key: string or byte array. It is recommended a 32 byte length |
| 197 | :param replace: if True, old value of internal secret_key is ignored and replaced. If false, a byte xor is used |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 198 | :return: None |
| 199 | """ |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 200 | if replace: |
| 201 | self.secret_key = None |
| 202 | self.secret_key = self._join_secret_key(new_secret_key) |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 203 | |
| 204 | def encrypt(self, value, schema_version=None, salt=None): |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 205 | """ |
| 206 | Encrypt a value |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 207 | :param value: value to be encrypted. It is string/unicode |
| 208 | :param schema_version: used for version control. If None or '1.0' no encryption is done. |
| 209 | If '1.1' symmetric AES encryption is done |
| 210 | :param salt: optional salt to be used. Must be str |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 211 | :return: Encrypted content of value |
| 212 | """ |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 213 | if not self.secret_key or not schema_version or schema_version == '1.0': |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 214 | return value |
| 215 | else: |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 216 | secret_key = self._join_secret_key(salt) |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 217 | cipher = AES.new(secret_key) |
| 218 | padded_private_msg = value + ('\0' * ((16-len(value)) % 16)) |
| 219 | encrypted_msg = cipher.encrypt(padded_private_msg) |
| 220 | encoded_encrypted_msg = b64encode(encrypted_msg) |
| 221 | return encoded_encrypted_msg.decode("ascii") |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 222 | |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 223 | def decrypt(self, value, schema_version=None, salt=None): |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 224 | """ |
| 225 | Decrypt an encrypted value |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 226 | :param value: value to be decrypted. It is a base64 string |
| 227 | :param schema_version: used for known encryption method used. If None or '1.0' no encryption has been done. |
| 228 | If '1.1' symmetric AES encryption has been done |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 229 | :param salt: optional salt to be used |
| 230 | :return: Plain content of value |
| 231 | """ |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 232 | if not self.secret_key or not schema_version or schema_version == '1.0': |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 233 | return value |
| 234 | else: |
| tierno | eef7cb7 | 2018-11-12 11:51:49 +0100 | [diff] [blame] | 235 | secret_key = self._join_secret_key(salt) |
| tierno | 136f295 | 2018-10-19 13:01:03 +0200 | [diff] [blame] | 236 | encrypted_msg = b64decode(value) |
| 237 | cipher = AES.new(secret_key) |
| 238 | decrypted_msg = cipher.decrypt(encrypted_msg) |
| 239 | unpadded_private_msg = decrypted_msg.decode().rstrip('\0') |
| 240 | return unpadded_private_msg |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 241 | |
| 242 | |
| 243 | def deep_update_rfc7396(dict_to_change, dict_reference, key_list=None): |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 244 | """ |
| 245 | Modifies one dictionary with the information of the other following https://tools.ietf.org/html/rfc7396 |
| 246 | Basically is a recursive python 'dict_to_change.update(dict_reference)', but a value of None is used to delete. |
| 247 | It implements an extra feature that allows modifying an array. RFC7396 only allows replacing the entire array. |
| 248 | For that, dict_reference should contains a dict with keys starting by "$" with the following meaning: |
| 249 | $[index] <index> is an integer for targeting a concrete index from dict_to_change array. If the value is None |
| 250 | the element of the array is deleted, otherwise it is edited. |
| 251 | $+[index] The value is inserted at this <index>. A value of None has not sense and an exception is raised. |
| 252 | $+ The value is appended at the end. A value of None has not sense and an exception is raised. |
| 253 | $val It looks for all the items in the array dict_to_change equal to <val>. <val> is evaluated as yaml, |
| 254 | that is, numbers are taken as type int, true/false as boolean, etc. Use quotes to force string. |
| 255 | Nothing happens if no match is found. If the value is None the matched elements are deleted. |
| 256 | $key: val In case a dictionary is passed in yaml format, if looks for all items in the array dict_to_change |
| 257 | that are dictionaries and contains this <key> equal to <val>. Several keys can be used by yaml |
| 258 | format '{key: val, key: val, ...}'; and all of them mast match. Nothing happens if no match is |
| 259 | found. If value is None the matched items are deleted, otherwise they are edited. |
| 260 | $+val If no match if found (see '$val'), the value is appended to the array. If any match is found nothing |
| 261 | is changed. A value of None has not sense. |
| 262 | $+key: val If no match if found (see '$key: val'), the value is appended to the array. If any match is found |
| 263 | nothing is changed. A value of None has not sense. |
| 264 | If there are several editions, insertions and deletions; editions and deletions are done first in reverse index |
| 265 | order; then insertions also in reverse index order; and finally appends in any order. So indexes used at |
| 266 | insertions must take into account the deleted items. |
| 267 | :param dict_to_change: Target dictionary to be changed. |
| 268 | :param dict_reference: Dictionary that contains changes to be applied. |
| 269 | :param key_list: This is used internally for recursive calls. Do not fill this parameter. |
| 270 | :return: none or raises and exception only at array modification when there is a bad format or conflict. |
| 271 | """ |
| 272 | def _deep_update_array(array_to_change, _dict_reference, _key_list): |
| 273 | to_append = {} |
| 274 | to_insert_at_index = {} |
| 275 | values_to_edit_delete = {} |
| 276 | indexes_to_edit_delete = [] |
| 277 | array_edition = None |
| 278 | _key_list.append("") |
| 279 | for k in _dict_reference: |
| 280 | _key_list[-1] = str(k) |
| 281 | if not isinstance(k, str) or not k.startswith("$"): |
| 282 | if array_edition is True: |
| 283 | raise DbException("Found array edition (keys starting with '$') and pure dictionary edition in the" |
| 284 | " same dict at '{}'".format(":".join(_key_list[:-1]))) |
| 285 | array_edition = False |
| 286 | continue |
| 287 | else: |
| 288 | if array_edition is False: |
| 289 | raise DbException("Found array edition (keys starting with '$') and pure dictionary edition in the" |
| 290 | " same dict at '{}'".format(":".join(_key_list[:-1]))) |
| 291 | array_edition = True |
| 292 | insert = False |
| 293 | indexes = [] # indexes to edit or insert |
| 294 | kitem = k[1:] |
| 295 | if kitem.startswith('+'): |
| 296 | insert = True |
| 297 | kitem = kitem[1:] |
| 298 | if _dict_reference[k] is None: |
| 299 | raise DbException("A value of None has not sense for insertions at '{}'".format( |
| 300 | ":".join(_key_list))) |
| 301 | |
| 302 | if kitem.startswith('[') and kitem.endswith(']'): |
| 303 | try: |
| 304 | index = int(kitem[1:-1]) |
| 305 | if index < 0: |
| 306 | index += len(array_to_change) |
| 307 | if index < 0: |
| 308 | index = 0 # skip outside index edition |
| 309 | indexes.append(index) |
| 310 | except Exception: |
| 311 | raise DbException("Wrong format at '{}'. Expecting integer index inside quotes".format( |
| 312 | ":".join(_key_list))) |
| 313 | elif kitem: |
| 314 | # match_found_skip = False |
| 315 | try: |
| 316 | filter_in = yaml.safe_load(kitem) |
| 317 | except Exception: |
| 318 | raise DbException("Wrong format at '{}'. Expecting '$<yaml-format>'".format(":".join(_key_list))) |
| 319 | if isinstance(filter_in, dict): |
| 320 | for index, item in enumerate(array_to_change): |
| 321 | for filter_k, filter_v in filter_in.items(): |
| 322 | if not isinstance(item, dict) or filter_k not in item or item[filter_k] != filter_v: |
| 323 | break |
| 324 | else: # match found |
| 325 | if insert: |
| 326 | # match_found_skip = True |
| 327 | insert = False |
| 328 | break |
| 329 | else: |
| 330 | indexes.append(index) |
| 331 | else: |
| 332 | index = 0 |
| 333 | try: |
| 334 | while True: # if not match a ValueError exception will be raise |
| 335 | index = array_to_change.index(filter_in, index) |
| 336 | if insert: |
| 337 | # match_found_skip = True |
| 338 | insert = False |
| 339 | break |
| 340 | indexes.append(index) |
| 341 | index += 1 |
| 342 | except ValueError: |
| 343 | pass |
| 344 | |
| 345 | # if match_found_skip: |
| 346 | # continue |
| 347 | elif not insert: |
| 348 | raise DbException("Wrong format at '{}'. Expecting '$+', '$[<index]' or '$[<filter>]'".format( |
| 349 | ":".join(_key_list))) |
| 350 | for index in indexes: |
| 351 | if insert: |
| 352 | if index in to_insert_at_index and to_insert_at_index[index] != _dict_reference[k]: |
| 353 | # Several different insertions on the same item of the array |
| 354 | raise DbException("Conflict at '{}'. Several insertions on same array index {}".format( |
| 355 | ":".join(_key_list), index)) |
| 356 | to_insert_at_index[index] = _dict_reference[k] |
| 357 | else: |
| 358 | if index in indexes_to_edit_delete and values_to_edit_delete[index] != _dict_reference[k]: |
| 359 | # Several different editions on the same item of the array |
| 360 | raise DbException("Conflict at '{}'. Several editions on array index {}".format( |
| 361 | ":".join(_key_list), index)) |
| 362 | indexes_to_edit_delete.append(index) |
| 363 | values_to_edit_delete[index] = _dict_reference[k] |
| 364 | if not indexes: |
| 365 | if insert: |
| 366 | to_append[k] = _dict_reference[k] |
| 367 | # elif _dict_reference[k] is not None: |
| 368 | # raise DbException("Not found any match to edit in the array, or wrong format at '{}'".format( |
| 369 | # ":".join(_key_list))) |
| 370 | |
| 371 | # edition/deletion is done before insertion |
| 372 | indexes_to_edit_delete.sort(reverse=True) |
| 373 | for index in indexes_to_edit_delete: |
| 374 | _key_list[-1] = str(index) |
| 375 | try: |
| 376 | if values_to_edit_delete[index] is None: # None->Anything |
| 377 | try: |
| 378 | del (array_to_change[index]) |
| 379 | except IndexError: |
| 380 | pass # it is not consider an error if this index does not exist |
| 381 | elif not isinstance(values_to_edit_delete[index], dict): # NotDict->Anything |
| 382 | array_to_change[index] = deepcopy(values_to_edit_delete[index]) |
| 383 | elif isinstance(array_to_change[index], dict): # Dict->Dict |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 384 | deep_update_rfc7396(array_to_change[index], values_to_edit_delete[index], _key_list) |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 385 | else: # Dict->NotDict |
| 386 | if isinstance(array_to_change[index], list): # Dict->List. Check extra array edition |
| 387 | if _deep_update_array(array_to_change[index], values_to_edit_delete[index], _key_list): |
| 388 | continue |
| 389 | array_to_change[index] = deepcopy(values_to_edit_delete[index]) |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 390 | # calling deep_update_rfc7396 to delete the None values |
| 391 | deep_update_rfc7396(array_to_change[index], values_to_edit_delete[index], _key_list) |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 392 | except IndexError: |
| 393 | raise DbException("Array edition index out of range at '{}'".format(":".join(_key_list))) |
| 394 | |
| 395 | # insertion with indexes |
| 396 | to_insert_indexes = list(to_insert_at_index.keys()) |
| 397 | to_insert_indexes.sort(reverse=True) |
| 398 | for index in to_insert_indexes: |
| 399 | array_to_change.insert(index, to_insert_at_index[index]) |
| 400 | |
| 401 | # append |
| 402 | for k, insert_value in to_append.items(): |
| 403 | _key_list[-1] = str(k) |
| 404 | insert_value_copy = deepcopy(insert_value) |
| 405 | if isinstance(insert_value_copy, dict): |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 406 | # calling deep_update_rfc7396 to delete the None values |
| 407 | deep_update_rfc7396(insert_value_copy, insert_value, _key_list) |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 408 | array_to_change.append(insert_value_copy) |
| 409 | |
| 410 | _key_list.pop() |
| 411 | if array_edition: |
| 412 | return True |
| 413 | return False |
| 414 | |
| 415 | if key_list is None: |
| 416 | key_list = [] |
| 417 | key_list.append("") |
| 418 | for k in dict_reference: |
| 419 | key_list[-1] = str(k) |
| 420 | if dict_reference[k] is None: # None->Anything |
| 421 | if k in dict_to_change: |
| 422 | del dict_to_change[k] |
| 423 | elif not isinstance(dict_reference[k], dict): # NotDict->Anything |
| 424 | dict_to_change[k] = deepcopy(dict_reference[k]) |
| 425 | elif k not in dict_to_change: # Dict->Empty |
| 426 | dict_to_change[k] = deepcopy(dict_reference[k]) |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 427 | # calling deep_update_rfc7396 to delete the None values |
| 428 | deep_update_rfc7396(dict_to_change[k], dict_reference[k], key_list) |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 429 | elif isinstance(dict_to_change[k], dict): # Dict->Dict |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 430 | deep_update_rfc7396(dict_to_change[k], dict_reference[k], key_list) |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 431 | else: # Dict->NotDict |
| 432 | if isinstance(dict_to_change[k], list): # Dict->List. Check extra array edition |
| 433 | if _deep_update_array(dict_to_change[k], dict_reference[k], key_list): |
| 434 | continue |
| 435 | dict_to_change[k] = deepcopy(dict_reference[k]) |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 436 | # calling deep_update_rfc7396 to delete the None values |
| 437 | deep_update_rfc7396(dict_to_change[k], dict_reference[k], key_list) |
| tierno | b3e750b | 2018-09-05 11:25:23 +0200 | [diff] [blame] | 438 | key_list.pop() |
| tierno | 87858ca | 2018-10-08 16:30:15 +0200 | [diff] [blame] | 439 | |
| 440 | |
| 441 | def deep_update(dict_to_change, dict_reference): |
| 442 | """ Maintained for backward compatibility. Use deep_update_rfc7396 instead""" |
| 443 | return deep_update_rfc7396(dict_to_change, dict_reference) |