Skip to content

Commit d6e104a

Browse files
committed
Added json file system
1 parent 2fd4ae5 commit d6e104a

File tree

3 files changed

+111
-23
lines changed

3 files changed

+111
-23
lines changed

filexdb/collection.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@
1414

1515

1616
class Collection:
17-
def __init__(self, col_name: str, binary_file: FileIO) -> None:
17+
def __init__(self, col_name: str, file_handler: FileIO) -> None:
1818
self._col_name = col_name
19-
self._binary_file = binary_file
19+
self._file_handler = file_handler
2020

2121
# Get the data of existing Database or empty database.
22-
self._database = self._binary_file.read()
22+
self._database = self._file_handler.read()
2323

2424
self._cursor: int = 0
2525

@@ -69,7 +69,7 @@ def insert(self, document: Mapping) -> str:
6969

7070
# print(self._database)
7171
# Write current state of Database into the Database-file
72-
self._binary_file.write(self._database)
72+
self._file_handler.write(self._database)
7373

7474
return _doc_id
7575
else:
@@ -99,9 +99,8 @@ def insert_all(self, document_list: List[Mapping]) -> List[str]:
9999

100100
return _doc_id
101101

102-
""" FIND_ONE
103-
def __find_one(self, query: Mapping = None) -> Document | None:
104-
"
102+
def __find_one(self, query: Mapping = None) -> Document | None: # Not works, right nom
103+
"""
105104
Finds a single ``Document`` of ``Collection``.
106105
107106
If ``query`` is None then returns all the ``Documents`` of ``Collection``.
@@ -110,7 +109,8 @@ def __find_one(self, query: Mapping = None) -> Document | None:
110109
111110
:param query: Condition to search Document
112111
:return: Document
113-
"
112+
"""
113+
114114
# Default result
115115
_result = {}
116116

@@ -131,7 +131,6 @@ def __find_one(self, query: Mapping = None) -> Document | None:
131131
_result = _result[self._cursor]
132132

133133
return _result
134-
"""
135134

136135
def find(self, query=None, limit=None) -> List[Document]:
137136
"""
@@ -208,7 +207,7 @@ def find(self, query=None, limit=None) -> List[Document]:
208207
self._reset_cursor()
209208

210209
# check if lower limit is valid or not
211-
if _limit_start >= len(_result):
210+
if _limit_start >= len(_result) and _limit_start != 0:
212211
raise ValueError(f"lower limit should be smaller than length of result")
213212
else:
214213
# Travers limited result
@@ -248,7 +247,7 @@ def delete(self, query=None) -> List[str]:
248247
self._collection.remove(_doc)
249248
_doc_id.append(_doc["_id_"])
250249

251-
self._binary_file.write(self._database)
250+
self._file_handler.write(self._database)
252251

253252
return _doc_id
254253

@@ -284,7 +283,7 @@ def update(self, document: Mapping, query=None) -> List[str]:
284283
_doc_id.append(_doc["_id_"])
285284

286285
# Write current state of Database
287-
self._binary_file.write(self._database)
286+
self._file_handler.write(self._database)
288287

289288
return _doc_id
290289

@@ -300,6 +299,15 @@ def count(self, query=None, limit: tuple = None) -> int:
300299

301300
return count
302301

302+
def rename(self, new_name: str) -> str:
303+
pass
304+
305+
def drop(self) -> str:
306+
pass
307+
308+
309+
310+
# ----------------------------------------------------------------#
303311
def _reset_cursor(self) -> None:
304312
"""
305313
Reset Cursor Pointer to 0th index

filexdb/database.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
from typing import Dict, Type, List
22

33
from .collection import Collection
4-
from .fileio import BinaryFileIO
4+
from .fileio import BinaryFileIO, JsonFileIO
55

66

77
class FileXdb:
88

9-
def __init__(self, db_name: str, data_dir: str = None):
9+
def __init__(self, db_name: str, data_dir=None, mode="binary"):
1010
"""
1111
Creates a Databased in ``data_dir`` Directory named ``db_name``.
1212
@@ -23,7 +23,10 @@ def __init__(self, db_name: str, data_dir: str = None):
2323
self._data_dir = data_dir
2424

2525
# Creating an instance of FileIO to Read Write Database-File.
26-
self._binary_file = BinaryFileIO(self._db_name, self._data_dir)
26+
if mode == "binary":
27+
self._file_handler = BinaryFileIO(self._db_name, self._data_dir)
28+
elif mode == "json":
29+
self._file_handler = JsonFileIO(self._db_name, self._data_dir)
2730

2831
def collection(self, col_name: str) -> Collection:
2932
"""
@@ -35,9 +38,13 @@ def collection(self, col_name: str) -> Collection:
3538
:return: An instance of Collection Baseclass.
3639
"""
3740
# Initiating collection
38-
collection = Collection(col_name, self._binary_file)
41+
collection = Collection(col_name, self._file_handler)
3942

4043
return collection
4144

4245
def show_collections(self):
4346
pass
47+
48+
49+
50+

filexdb/fileio.py

Lines changed: 80 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def write(self, data: dict):
7171

7272

7373
class BinaryFileIO(FileIO):
74-
def __init__(self, db_name: str, data_dir: str = None):
74+
def __init__(self, db_name: str, data_dir=None):
7575
"""
7676
Create a new instance.
7777
@@ -87,7 +87,7 @@ def __init__(self, db_name: str, data_dir: str = None):
8787

8888
self._data_dir = data_dir
8989

90-
# Adding ``FileXdb`` specific file extention to the Database-file.
90+
# Adding ``FileXdb`` specific file extension to the Database-file.
9191
self._db_name = f"{db_name}.fxdb"
9292

9393
# Setting default Database-file path.
@@ -132,7 +132,7 @@ def read(self) -> dict:
132132
raise IOError(f"Cannot read file.\n\t`{self._db_name}` is not a database")
133133

134134
else:
135-
# Returns an empty dict as
135+
# Initiate an empty dict as
136136
database = {}
137137

138138
return database
@@ -167,12 +167,85 @@ def write(self, data: dict) -> None:
167167

168168

169169
class JsonFileIO(FileIO):
170-
def __init__(self, db_name):
170+
def __init__(self, db_name:str, data_dir=None):
171+
171172
super().__init__()
172-
self.db_name = db_name
173+
174+
self._data_dir = data_dir
175+
176+
# Adding ``JSON`` file extension to the Database-file.
177+
self._db_name = f"{db_name}.json"
178+
179+
# Setting default Database-file path.
180+
self._db_file_path = self._db_name
181+
182+
# Checking if Data Directory is on root or not.
183+
if self._data_dir is not None:
184+
# Creating Database-file full path by joining data_dir & db_name.
185+
self._db_file_path = os.path.join(self._data_dir, self._db_name)
186+
187+
# Create the Database/File if it doesn't exist
188+
create_db(self._db_name, self._data_dir)
173189

174190
def read(self) -> dict:
175-
pass
191+
"""
192+
Reads existing Database-file, either it is empty or non-empty.
193+
194+
If empty returns an empty dict, else returns saved Data.
195+
196+
:return: Database as a python Dictionary.
197+
"""
198+
database = None
199+
200+
with open(self._db_file_path, "r") as file:
201+
202+
# Get the file size by moving the cursor to the file end and reading its location.
203+
file.seek(0, os.SEEK_END)
204+
size = file.tell()
205+
206+
# check if size of file is 0
207+
if size:
208+
# Bring the cursor to the beginning of Database-file
209+
file.seek(0)
210+
211+
try:
212+
# Load whole Database form Database-file
213+
database = json.load(file)
214+
215+
except io.UnsupportedOperation:
216+
# Through an Unsupported Operation Error.
217+
raise IOError(f"Cannot read file.\n\t`{self._db_name}` is not a database")
218+
219+
else:
220+
# Initiate an empty dict as
221+
database = {}
222+
223+
return database
176224

177225
def write(self, data: dict):
178-
pass
226+
"""
227+
Write the current state of entire Database to the Database-file.
228+
229+
:param data: Dictionary object to write on Database.
230+
:return: None.
231+
"""
232+
with open(self._db_file_path, "w") as file:
233+
234+
# Move the cursor to the beginning of the file just in case.
235+
file.seek(0)
236+
237+
# Serialize the database state using the user-provided arguments
238+
serialized = json.dumps(data, indent=4)
239+
240+
# Write the serialized data to the file
241+
try:
242+
file.write(serialized)
243+
except io.UnsupportedOperation:
244+
raise IOError(f"Cannot write to the file.\n\t`{self._db_name}` is not a database")
245+
246+
# Ensure the file has been written
247+
file.flush()
248+
os.fsync(file.fileno())
249+
250+
# Remove data that is behind the new cursor if the file has gotten shorter.
251+
file.truncate()

0 commit comments

Comments
 (0)