-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsondb.py
279 lines (192 loc) · 8.23 KB
/
jsondb.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import json
import os
class JsonDB:
"""This is my JSON database. It uses JSON to store data in tables."""
def __init__(self, filename: str):
self.filename: str = filename
# Ensure the file exists with an empty dictionary
try:
with open(self.filename, "r") as file:
db = json.load(file)
if not isinstance(db, dict):
raise ValueError(f"The content of {self.filename} is not a valid dictionary.")
except (FileNotFoundError, json.JSONDecodeError, ValueError):
with open(self.filename, "w") as file:
json.dump({}, file, indent=4)
def create_table(self, table_name: str):
"""Add a new table to the database."""
with open(self.filename, "r") as file:
db = json.load(file)
if table_name not in db:
db[table_name] = [] # Initialize the table with an empty list
with open(self.filename, "w") as file:
json.dump(db, file, indent=4)
return self
def add_data(self, table_name: str, **data):
"""Add a new record to a specific table."""
with open(self.filename, "r") as file:
db = json.load(file)
if table_name not in db:
db[table_name] = []
db[table_name].append(data)
with open(self.filename, "w") as file:
json.dump(db, file, indent=4)
return self
def delete_data(self, table_name: str, index: int) -> tuple[str, bool]:
"""Delete a record by its index from a specific table."""
with open(self.filename, "r") as file:
db = json.load(file)
try:
if table_name not in db:
return f"Table '{table_name}' does not exist", False
db[table_name].pop(index)
except IndexError:
return f"Data at index {index} does not exist", False
with open(self.filename, "w") as file:
json.dump(db, file, indent=4)
return f"Data at index {index} deleted from table '{table_name}'", True
def update_data(self, table_name: str, index: int, **new_data) -> tuple[str, bool]:
"""Update a specific record in the table by its index."""
with open(self.filename, "r") as file:
db = json.load(file)
try:
if table_name not in db:
return f"Table '{table_name}' does not exist", False
if index < 0 or index >= len(db[table_name]):
return f"Data at index {index} does not exist in table '{table_name}'", False
# Update the existing data with new data
db[table_name][index].update(new_data)
except IndexError:
return f"Data at index {index} does not exist", False
with open(self.filename, "w") as file:
json.dump(db, file, indent=4)
return f"Data at index {index} updated successfully in table '{table_name}'", True
def get_data(self, table_name: str) -> list:
"""Retrieve all data from a specific table."""
with open(self.filename, "r") as file:
db = json.load(file)
if table_name not in db:
return []
return db[table_name]
def exists(self, table_name: str, **data) -> bool:
"""Check if a specific record exists in the table."""
with open(self.filename, "r") as file:
db = json.load(file)
if table_name not in db:
return False
for record in db[table_name]:
if all(record.get(k) == v for k, v in data.items()):
return True
return False
def get_data_by(self, search_key: str, search_value):
"""
Retrieve all records matching a specific key-value pair.
:param search_key: The key to search for (e.g., 'name').
:param search_value: The value to match (e.g., 'Alice').
:return: List of matching records.
"""
with open(self.filename, "r") as file:
db = json.load(file)
matching_records = []
for table in db.values(): # Iterate through all tables
for record in table: # Iterate through records
if record.get(search_key) == search_value: # Check for matching key-value
matching_records.append(record)
return matching_records
def update_data(self, table_name: str, key: str, old_value, new_value):
"""
Update the value of a specific key in the record of the specified table.
:param table_name: The table to update (e.g., 'users').
:param key: The key whose value needs to be updated.
:param old_value: The current value of the key to be replaced.
:param new_value: The new value to set for the key.
"""
with open(self.filename, "r") as file:
db = json.load(file)
# Check if the table exists
if table_name not in db:
raise ValueError(f"Table '{table_name}' does not exist.")
# Find the record and update it
updated = False
for record in db[table_name]:
if record.get(key) == old_value:
record[key] = new_value
updated = True
break
if not updated:
raise ValueError(f"Record with {key} = {old_value} not found in table '{table_name}'.")
# Save the updated data
with open(self.filename, "w") as file:
json.dump(db, file, indent=4)
return self
def delete_table(self, table_name: str):
"""Delete all data in a specific table."""
with open(self.filename, 'r') as file:
db = json.load(file)
if table_name in db:
db[table_name] = [] # Clear all data in the table
with open(self.filename, 'w') as file:
json.dump(db, file, indent=4)
return f"All data in '{table_name}' table has been deleted."
def get_all_data(self):
with open(self.filename, 'r') as file:
db = json.load(file)
return db
def delete_all(self):
with open(self.filename, 'w') as file:
json.dump({}, file)
return True
def delete_db(self):
os.remove(self.filename)
return True
# old JsonDB
# import json
# class JsonDB:
# """This is my JSON database, it uses JSON to store data"""
# def __init__(self, filename):
# self.filename: str = filename
# def add_table(self, table_name: str):
# with open(self.filename, "r") as file:
# db = json.load(file)
# db[table_name] = {}
# with open(self.filename, "w") as file:
# json.dump(db, file, indent=4)
# return self
# def add_data(self, **data):
# try:
# with open(self.filename, "r") as file:
# db = json.load(file)
# except (FileNotFoundError, json.JSONDecodeError):
# db = []
# db.append(data)
# with open(self.filename, "w") as file:
# json.dump(db, file, indent=4)
# return self
# def get_data(self) -> list[str]:
# with open(self.filename, 'r') as f:
# return json.load(f)
# def delete_data(self, id: int) -> tuple[str, bool]:
# with open(self.filename, 'r') as file:
# db = json.load(file)
# # Ensure the id is within valid range
# if 0 <= id < len(db):
# db.pop(id)
# else:
# return f"Data with id {id} does not exist", False
# with open(self.filename, 'w') as file:
# json.dump(db, file, indent=4)
# return self
# def exists(self, **data) -> bool:
# with open(self.filename, 'r') as file:
# db = json.load(file)
# # Iterate through the database and check for the exact match
# for i in db:
# if i == data:
# return True
# return False # Return False only after checking all entries
# def delete_all(self, brackets_also: bool = True):
# with open(self.filename, 'w') as file:
# if brackets_also:
# file.write('')
# else:
# json.dump([], file, indent=4)