dictature 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dictature/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .dictature import Dictature
@@ -0,0 +1,3 @@
1
+ from .mock import DictatureBackendMock, ValueMode, Value
2
+ from .directory import DictatureBackendDirectory
3
+ from .sqlite import DictatureBackendSQLite
@@ -0,0 +1,79 @@
1
+ from re import sub
2
+ from json import dumps, loads
3
+ from pathlib import Path
4
+ from typing import Iterable, Union
5
+ from shutil import rmtree
6
+
7
+ from .mock import DictatureTableMock, DictatureBackendMock, Value, ValueMode
8
+
9
+
10
+ class DictatureBackendDirectory(DictatureBackendMock):
11
+ def __init__(self, directory: Union[Path, str], dir_prefix: str = 'db_') -> None:
12
+ if isinstance(directory, str):
13
+ directory = Path(directory)
14
+ self.__directory = directory
15
+ self.__dir_prefix = dir_prefix
16
+
17
+ def keys(self) -> Iterable[str]:
18
+ for child in self.__directory.iterdir():
19
+ if child.is_dir() and child.name.startswith(self.__dir_prefix):
20
+ yield child.name[len(self.__dir_prefix):]
21
+
22
+ def table(self, name: str) -> 'DictatureTableMock':
23
+ return DictatureTableDirectory(self.__directory, name, self.__dir_prefix)
24
+
25
+
26
+ class DictatureTableDirectory(DictatureTableMock):
27
+ def __init__(self, path_root: Path, name: str, db_prefix: str, prefix: str = 'item_') -> None:
28
+ self.__path = path_root / (db_prefix + self.__filename_encode(name, suffix=''))
29
+ self.__prefix = prefix
30
+
31
+ def keys(self) -> Iterable[str]:
32
+ for child in self.__path.iterdir():
33
+ if child.is_file() and child.name.startswith(self.__prefix) and not child.name.endswith('.tmp'):
34
+ yield self.__filename_decode(child.name[len(self.__prefix):])
35
+
36
+ def drop(self) -> None:
37
+ rmtree(self.__path)
38
+
39
+ def create(self) -> None:
40
+ self.__path.mkdir(parents=True, exist_ok=True)
41
+
42
+ def set(self, item: str, value: Value) -> None:
43
+ file_target = self.__item_path(item)
44
+ file_target_tmp = file_target.with_suffix('.tmp')
45
+
46
+ save_as_json = value.mode != ValueMode.string.value or value.value.startswith('{')
47
+ save_data = dumps({'value': value.value, 'mode': value.mode}, indent=1) if save_as_json else value.value
48
+
49
+ file_target_tmp.write_text(save_data)
50
+ file_target_tmp.rename(file_target)
51
+
52
+ def get(self, item: str) -> Value:
53
+ try:
54
+ save_data = self.__item_path(item).read_text()
55
+ if save_data.startswith('{'):
56
+ data = loads(save_data)
57
+ return Value(data['value'], data['mode'])
58
+ return Value(save_data, ValueMode.string.value)
59
+ except FileNotFoundError:
60
+ raise KeyError(item)
61
+
62
+ def delete(self, item: str) -> None:
63
+ if self.__item_path(item).exists():
64
+ self.__item_path(item).unlink()
65
+
66
+ def __item_path(self, item: str) -> Path:
67
+ return self.__path / (self.__prefix + self.__filename_encode(item))
68
+
69
+ @staticmethod
70
+ def __filename_encode(name: str, suffix: str = '.txt') -> str:
71
+ if name == sub(r'[^\w_. -]', '_', name):
72
+ return f"d_{name}{suffix}"
73
+ return f'e_{name.encode('utf-8').hex()}{suffix}'
74
+
75
+ @staticmethod
76
+ def __filename_decode(name: str) -> str:
77
+ if name.startswith('d_'):
78
+ return name[2:-5]
79
+ return bytes.fromhex(name[2:-5]).decode('utf-8')
@@ -0,0 +1,41 @@
1
+ from typing import Iterable, NamedTuple
2
+ from enum import Enum
3
+
4
+
5
+ class ValueMode(Enum):
6
+ string = 0
7
+ json = 1
8
+ pickle = 2
9
+
10
+
11
+ class Value(NamedTuple):
12
+ value: str
13
+ mode: int
14
+
15
+
16
+ class DictatureBackendMock:
17
+ def keys(self) -> Iterable[str]:
18
+ raise NotImplementedError("This method should be implemented by the subclass")
19
+
20
+ def table(self, name: str) -> 'DictatureTableMock':
21
+ raise NotImplementedError("This method should be implemented by the subclass")
22
+
23
+
24
+ class DictatureTableMock:
25
+ def keys(self) -> Iterable[str]:
26
+ raise NotImplementedError("This method should be implemented by the subclass")
27
+
28
+ def drop(self) -> None:
29
+ raise NotImplementedError("This method should be implemented by the subclass")
30
+
31
+ def create(self) -> None:
32
+ raise NotImplementedError("This method should be implemented by the subclass")
33
+
34
+ def set(self, item: str, value: Value) -> None:
35
+ raise NotImplementedError("This method should be implemented by the subclass")
36
+
37
+ def get(self, item: str) -> Value:
38
+ raise NotImplementedError("This method should be implemented by the subclass")
39
+
40
+ def delete(self, item: str) -> None:
41
+ raise NotImplementedError("This method should be implemented by the subclass")
@@ -0,0 +1,137 @@
1
+ import sqlite3
2
+ from typing import Iterable, Union, Optional
3
+ from pathlib import Path
4
+
5
+ from .mock import DictatureBackendMock, DictatureTableMock, Value, ValueMode
6
+
7
+
8
+ class DictatureBackendSQLite(DictatureBackendMock):
9
+ def __init__(self, file: Union[str, Path]) -> None:
10
+ if isinstance(file, str):
11
+ file = Path(file)
12
+ self.__file = file
13
+ self.__connection = sqlite3.connect(
14
+ f"{self.__file.absolute()}",
15
+ check_same_thread=False if sqlite3.threadsafety >= 3 else True
16
+ )
17
+ self.__cursor = self.__connection.cursor()
18
+
19
+ def keys(self) -> Iterable[str]:
20
+ tables = self._execute("SELECT tbl_name FROM sqlite_master WHERE type='table' AND tbl_name LIKE 'db_%'")
21
+ return {table[0][3:] for table in tables}
22
+
23
+ def table(self, name: str) -> 'DictatureTableMock':
24
+ return DictatureTableSQLite(self, name)
25
+
26
+ def _execute(self, query: str, data: tuple = ()) -> list:
27
+ return list(self.__cursor.execute(query, data))
28
+
29
+ def _commit(self) -> None:
30
+ self.__connection.commit()
31
+
32
+ def __del__(self):
33
+ self.__connection.close()
34
+
35
+
36
+
37
+ class DictatureTableSQLite(DictatureTableMock):
38
+ def __init__(self, parent: "DictatureBackendSQLite", name: str) -> None:
39
+ self.__parent = parent
40
+ self.__supports_jsonization: Optional[bool] = None
41
+ self.__table = "`tb_%s`" % name.replace('`', '``')
42
+
43
+ def keys(self) -> Iterable[str]:
44
+ # noinspection PyProtectedMember
45
+ return set(map(lambda x: x[0], self.__parent._execute(f"SELECT key FROM {self.__table}")))
46
+
47
+ def drop(self) -> None:
48
+ # noinspection PyProtectedMember
49
+ self.__parent._execute(f"DROP TABLE {self.__table}")
50
+
51
+ def key_exists(self, item: str) -> bool:
52
+ # noinspection PyProtectedMember
53
+ return not not self.__parent._execute(f"SELECT value FROM {self.__table} WHERE key=?", (item,))
54
+
55
+ def create(self) -> None:
56
+ # noinspection PyProtectedMember
57
+ self.__parent._execute(f"""
58
+ CREATE TABLE IF NOT EXISTS {self.__table} (
59
+ `key` TEXT NOT NULL UNIQUE,
60
+ `value` TEXT
61
+ );
62
+ """)
63
+
64
+ def set(self, item: str, value: Value) -> None:
65
+ if value.mode != ValueMode.string:
66
+ self.__support_jsonization()
67
+
68
+ if self.key_exists(item):
69
+ if self.__test_supports_jsonization():
70
+ # noinspection PyProtectedMember
71
+ self.__parent._execute(f"""
72
+ UPDATE {self.__table} SET value=?, jsonized=? WHERE key=?
73
+ """, (value.value, value.mode, item))
74
+ else:
75
+ # noinspection PyProtectedMember
76
+ self.__parent._execute(f"UPDATE {self.__table} SET value=? WHERE key=?", (value.value, item))
77
+ else:
78
+ if self.__test_supports_jsonization():
79
+ # noinspection PyProtectedMember
80
+ self.__parent._execute(
81
+ f"INSERT INTO {self.__table} (`key`,`value`,`jsonized`) VALUES (?,?,?);",
82
+ (item, value.value, value.mode)
83
+ )
84
+ else:
85
+ # noinspection PyProtectedMember
86
+ self.__parent._execute(
87
+ f"INSERT INTO {self.__table} (`key`,`value`) VALUES (?,?);", (item, value.value)
88
+ )
89
+ # noinspection PyProtectedMember
90
+ self.__parent._commit()
91
+
92
+ def get(self, item: str) -> Value:
93
+ if self.__test_supports_jsonization():
94
+ cmd = f"SELECT value, jsonized FROM {self.__table} WHERE key=?"
95
+ else:
96
+ cmd = f"SELECT value FROM {self.__table} WHERE key=?"
97
+
98
+ # noinspection PyProtectedMember
99
+ r = self.__parent._execute(cmd, (item,))
100
+ if r:
101
+ value: str = r[0][0]
102
+
103
+ if self.__supports_jsonization:
104
+ jsonized_state: int = r[0][1]
105
+ else:
106
+ jsonized_state = ValueMode.string.value
107
+
108
+ return Value(value=value, mode=jsonized_state)
109
+ raise KeyError(item)
110
+
111
+ def delete(self, item: str) -> None:
112
+ # noinspection PyProtectedMember
113
+ self.__parent._execute(
114
+ f"DELETE FROM {self.__table} WHERE `key`=?;", (item,)
115
+ )
116
+ # noinspection PyProtectedMember
117
+ self.__parent._commit()
118
+
119
+ def __test_supports_jsonization(self) -> bool:
120
+ if self.__supports_jsonization is not None:
121
+ return self.__supports_jsonization
122
+ # noinspection PyProtectedMember
123
+ for _, column_name, _, _, _, _ in self.__parent._execute(f"PRAGMA table_info({self.__table})"):
124
+ if column_name == 'jsonized':
125
+ self.__supports_jsonization = True
126
+ return True
127
+ self.__supports_jsonization = False
128
+ return False
129
+
130
+ def __support_jsonization(self) -> None:
131
+ if self.__supports_jsonization or self.__test_supports_jsonization():
132
+ return
133
+ # noinspection PyProtectedMember
134
+ self.__parent._execute(f"""
135
+ ALTER TABLE {self.__table} ADD COLUMN jsonized INTEGER NOT NULL DEFAULT 0
136
+ """)
137
+ self.__supports_jsonization = True
dictature/dictature.py ADDED
@@ -0,0 +1,126 @@
1
+ import json
2
+ import pickle
3
+ from gzip import compress, decompress
4
+ from base64 import b64encode, b64decode
5
+ from random import choice
6
+ from typing import Optional, Dict, Any, Set, Iterator, Tuple
7
+
8
+ from .backend import DictatureBackendMock, ValueMode, Value
9
+
10
+
11
+ class Dictature:
12
+ def __init__(self, backend: DictatureBackendMock) -> None:
13
+ self.__db = backend
14
+ self.__db_cache: Dict[str, "DictatureTable"] = {}
15
+
16
+ def keys(self) -> Set[str]:
17
+ return set(self.__db.keys())
18
+
19
+ def values(self) -> Iterator["DictatureTable"]:
20
+ return map(lambda x: x[1], self.items())
21
+
22
+ def items(self) -> Iterator[Tuple[str, "DictatureTable"]]:
23
+ for k in self.keys():
24
+ yield k, self[k]
25
+
26
+ def to_dict(self) -> Dict[str, Any]:
27
+ return {k: v.to_dict() for k, v in self.items()}
28
+
29
+ def __str__(self):
30
+ return str(self.to_dict())
31
+
32
+ def __getitem__(self, item: str) -> "DictatureTable":
33
+ if len(self.__db_cache) > 128:
34
+ del self.__db_cache[choice(list(self.__db_cache.keys()))]
35
+ if item not in self.__db_cache:
36
+ self.__db_cache[item] = DictatureTable(self.__db, item)
37
+ return self.__db_cache[item]
38
+
39
+ def __delitem__(self, key: str) -> None:
40
+ self[key].drop()
41
+
42
+ def __contains__(self, item: str) -> bool:
43
+ return item in self.keys()
44
+
45
+ def __bool__(self) -> bool:
46
+ return not not self.keys()
47
+
48
+
49
+ class DictatureTable:
50
+ def __init__(self, db: DictatureBackendMock, table_name: str):
51
+ self.__db = db
52
+ self.__table = self.__db.table(table_name)
53
+ self.__table_created = False
54
+
55
+ def get(self, item: str, default: Optional[Any] = None) -> Any:
56
+ try:
57
+ return self[item]
58
+ except KeyError:
59
+ return default
60
+
61
+ def key_exists(self, item: str) -> bool:
62
+ self.__create_table()
63
+ return item in self.keys()
64
+
65
+ def keys(self) -> Set[str]:
66
+ self.__create_table()
67
+ return set(self.__table.keys())
68
+
69
+ def values(self) -> Iterator[Any]:
70
+ return map(lambda x: x[1], self.items())
71
+
72
+ def items(self) -> Iterator[Tuple[str, Any]]:
73
+ for k in self.keys():
74
+ yield k, self[k]
75
+
76
+ def drop(self) -> None:
77
+ self.__create_table()
78
+ self.__table.drop()
79
+
80
+ def to_dict(self) -> Dict[str, Any]:
81
+ return {k: v for k, v in self.items()}
82
+
83
+ def __str__(self):
84
+ return str(self.to_dict())
85
+
86
+ def __getitem__(self, item: str) -> Any:
87
+ self.__create_table()
88
+ value = self.__table.get(item)
89
+ mode = ValueMode(value.mode)
90
+ match mode:
91
+ case ValueMode.string:
92
+ return value.value
93
+ case ValueMode.json:
94
+ return json.loads(value.value)
95
+ case ValueMode.pickle:
96
+ return pickle.loads(decompress(b64decode(value.value.encode('ascii'))))
97
+ raise ValueError(f"Unknown mode '{value.mode}'")
98
+
99
+ def __setitem__(self, key: str, value: Any) -> None:
100
+ self.__create_table()
101
+ value_mode = ValueMode.string
102
+
103
+ if type(value) is not str:
104
+ try:
105
+ value = json.dumps(value)
106
+ value_mode = ValueMode.json
107
+ except TypeError:
108
+ value = b64encode(compress(pickle.dumps(value))).decode('ascii')
109
+ value_mode = value_mode.pickle
110
+
111
+ self.__table.set(key, Value(value=value, mode=value_mode.value))
112
+
113
+ def __delitem__(self, key: str) -> None:
114
+ self.__table.delete(key)
115
+
116
+ def __contains__(self, item: str):
117
+ return item in self.keys()
118
+
119
+ def __bool__(self) -> bool:
120
+ return not not self.keys()
121
+
122
+ def __create_table(self) -> None:
123
+ if self.__table_created:
124
+ return
125
+ self.__table.create()
126
+ self.__table_created = True
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Adam Hlaváček
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.1
2
+ Name: dictature
3
+ Version: 0.9.0
4
+ Summary: dictature -- A generic wrapper around dict-like interface with mulitple backends
5
+ Author-email: Adam Hlavacek <git@adamhlavacek.com>
6
+ Project-URL: Homepage, https://github.com/esoadamo/dictature
7
+ Project-URL: Issues, https://github.com/esoadamo/dictature/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+
14
+ # SQLiDictature
15
+
16
+ A wrapper for Python's dictionary with multiple backends.
17
+
18
+ ## Installation
19
+
20
+ ```shell
21
+ pip install dictature
22
+ ```
23
+
24
+ ## Dictature usage
25
+ This package also includes a class that allows you to use your SQLite db as a Python dictionary:
26
+
27
+ ```python
28
+ from dictature import Dictature
29
+ from dictature.backend import DictatureBackendDirectory, DictatureBackendSQLite
30
+
31
+ # will use/create the db directory
32
+ # dictionary = Dictature(DictatureBackendDirectory('test_data'))
33
+ # will use/create the db file
34
+ dictionary = Dictature(DictatureBackendSQLite('test_data.sqlite3'))
35
+
36
+ # will create a table db_test and there a row called foo with value bar
37
+ dictionary['test']['foo'] = 'bar'
38
+
39
+ # also support anything that can be jsonized
40
+ dictionary['test']['list'] = ['1', 2, True]
41
+ print(dictionary['test']['list']) # prints ['1', 2, True]
42
+
43
+ # or anything, really (that can be serialized with pickle)
44
+ from threading import Thread
45
+ dictionary['test']['thread'] = Thread
46
+ print(dictionary['test']['thread']) # prints <class 'threading.Thread'>
47
+
48
+ # and deleting
49
+ del dictionary['test']['list'] # deletes the record
50
+ del dictionary['test'] # drops whole table
51
+ ```
@@ -0,0 +1,11 @@
1
+ dictature/__init__.py,sha256=UCPJKHeyirRZ0pCYoyeat-rwXa8pDezOJ3UWCipDdyc,33
2
+ dictature/dictature.py,sha256=CwIK8pQyFq7JTqF_CEhqE4_w0TXlxZAVLfO0wRccCcU,3800
3
+ dictature/backend/__init__.py,sha256=d5s6QCJOUzFglVNg8Cqqx_8b61S-AOTGjEUIF6FS69U,149
4
+ dictature/backend/directory.py,sha256=xdjXL7pBh_sG85sST6nZIruWVS8aJnUrk4erEEslaU4,3054
5
+ dictature/backend/mock.py,sha256=Qd7KSh-qM763Jc7biDf5xYFWdgDax30dUHh2gXWwTZE,1266
6
+ dictature/backend/sqlite.py,sha256=VvEivK40NNGhOc-J4y9b81Fs9RDaDUw1jHXqKxqZQqI,5130
7
+ dictature-0.9.0.dist-info/LICENSE,sha256=n1U9DKr8sM5EY2QHcvxSGiKTDWUT8MyXsOC79w94MT0,1072
8
+ dictature-0.9.0.dist-info/METADATA,sha256=T5PMGmS_ceBGoXTDHn5W2iMp4v-ftL0zd825aPJ4DcY,1670
9
+ dictature-0.9.0.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
10
+ dictature-0.9.0.dist-info/top_level.txt,sha256=-RO39WWCF44lqiXhSUcACVqbk6SkgReZTz7ZmHKH3-U,10
11
+ dictature-0.9.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ dictature