-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
105 lines (89 loc) · 3.04 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# Copyright (C) 2021 Armando Neto <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import json
import sqlite3
class Database:
"""Simple dict-like (key/value) database interface powered by SQLite3 and json.
Create a database
>>> db = Database(path='test_database.sqlite3')
Work with strings
>>> db['a'] = 'letter A'
>>> db['a']
'letter A'
Work with dicts
>>> db['d'] = {'key': 'value'}
>>> db['d']
{'key': 'value'}
>>> type(db['d'])
<class 'dict'>
Get all keys
>>> db.keys()
['a', 'd']
>>> len(db)
2
Items can be deleted
>>> del db['d']
>>> del db['a']
>>> db['a']
Traceback (most recent call last):
...
KeyError: 'a'
>>> db.keys()
[]
>>> len(db)
0
"""
def __init__(self, path, key_lenght=1000):
self.path = path
self._create(key_lenght=key_lenght)
def _connect(self):
return sqlite3.connect(self.path)
def _create(self, key_lenght):
connection = self._connect()
cursor = connection.cursor()
cursor.execute(
"CREATE TABLE IF NOT EXISTS kv_table"
"(key varchar(%s) PRIMARY KEY, value JSON)"
% key_lenght
)
def __getitem__(self, key):
with self._connect() as connection:
cursor = connection.execute(
"SELECT value FROM kv_table WHERE key=? LIMIT 1", (key,))
value = cursor.fetchone()
if value is not None:
value = value[0]
return json.loads(value)
raise KeyError(key)
def __setitem__(self, key, value):
with self._connect() as connection:
connection.execute(
"INSERT INTO kv_table VALUES(?, json(?))"
"ON CONFLICT(key) DO UPDATE set value = json(?)",
(key, json.dumps(value), json.dumps(value)),
)
def __delitem__(self, key):
with self._connect() as connection:
connection.execute("DELETE FROM kv_table WHERE key=?", (key))
def __len__(self):
with self._connect() as connection:
cursor = connection.execute("SELECT count(*) FROM kv_table")
value = cursor.fetchone()
return value[0]
def keys(self):
with self._connect() as connection:
cursor = connection.execute("SELECT key FROM kv_table")
values = cursor.fetchall()
return [v[0] for v in values]