]> git.mxchange.org Git - fba.git/blob - fba/cache.py
22c2b00ba2ae725d4416d08b5f40f624fb5c4cfc
[fba.git] / fba / cache.py
1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published
6 # by the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17 # Cache for redundant SQL queries
18 _cache = {}
19
20 ##### Cache #####
21
22 def key_exists(key: str) -> bool:
23     return key in _cache
24
25 def set_all(key: str, rows: list, value: any):
26     # DEBUG: print(f"DEBUG: key='{key}',rows()={len(rows)},value[]={type(value)} - CALLED!")
27     if type(key) != str:
28         raise ValueError("Parameter key[]='{type(key)}' is not 'str'")
29     elif not key_exists(key):
30         # DEBUG: print(f"DEBUG: Cache for key='{key}' not initialized.")
31         _cache[key] = {}
32
33     for sub in rows:
34         # DEBUG: print(f"DEBUG: Setting key='{key}',sub[{type(sub)}]='{sub}'")
35
36         if isinstance(sub, tuple):
37             _cache[key][sub[0]] = value
38         else:
39             print(f"WARNING: Unsupported type row[]='{type(row)}'")
40
41     # DEBUG: print("DEBUG: EXIT!")
42
43 def set_sub_key(key: str, sub: str, value: any):
44     if type(key) != str:
45         raise ValueError("Parameter key[]='{type(key)}' is not 'str'")
46     elif type(sub) != str:
47         raise ValueError("Parameter sub[]='{type(sub)}' is not 'str'")
48     elif not key_exists(key):
49         print(f"WARNING: Bad method call, key='{key}' is not initialized yet.")
50         raise Exception(f"Cache for key='{key}' is not initialized, but function invoked")
51
52     _cache[key][sub] = value
53
54 def sub_key_exists(key: str, sub: str) -> bool:
55     if type(key) != str:
56         raise ValueError("Parameter key[]='{type(key)}' is not 'str'")
57     elif type(sub) != str:
58         raise ValueError("Parameter sub[]='{type(sub)}' is not 'str'")
59     elif not key_exists(key):
60         print(f"WARNING: Bad method call, key='{key}' is not initialized yet.")
61         raise Exception(f"Cache for key='{key}' is not initialized, but function invoked")
62
63     return sub in _cache[key]