|
1 | | -from .document import Document |
2 | 1 | import json |
3 | 2 |
|
| 3 | +from .document import Document |
| 4 | +from .fileio import FileIO, BinaryFileIO |
| 5 | + |
4 | 6 |
|
5 | 7 | class Collection: |
6 | | - def __init__(self, database, db_name, col_name: str) -> None: |
7 | | - self._database = database |
8 | | - self._db_name = db_name |
| 8 | + def __init__(self, col_name: str, binary_file: FileIO) -> None: |
9 | 9 | self._col_name = col_name |
| 10 | + self._binary_file = binary_file |
| 11 | + |
| 12 | + # Get the data of existing Database or empty database. |
| 13 | + self._database = self._binary_file.read() |
| 14 | + # print(self._database) |
| 15 | + # Initiate a default Collection |
| 16 | + |
| 17 | + # Check the Collection is already exists or no |
| 18 | + if self._col_name in self._database.keys(): |
| 19 | + |
| 20 | + # Get the existing Collection |
| 21 | + self._collection: list = self._database[self._col_name] |
| 22 | + |
| 23 | + else: |
| 24 | + # Create new Collection |
| 25 | + self._database[self._col_name] = [] |
| 26 | + self._collection: list = self._database[self._col_name] |
| 27 | + |
| 28 | + def insert(self, document: dict) -> None: |
| 29 | + """ |
| 30 | + Inserts a single Document into the Database. |
| 31 | +
|
| 32 | + Document should be JSON Object. |
| 33 | +
|
| 34 | + :param document: Document to insert into database |
| 35 | + :return: None |
| 36 | + """ |
| 37 | + |
| 38 | + # Append the document into the Collection |
| 39 | + self._collection.append(document) |
| 40 | + |
| 41 | + # Add modified Collection to Database |
| 42 | + self._database[self._col_name] = self._collection |
| 43 | + # print(self._database) |
| 44 | + # Write current state of Database into the Database-file |
| 45 | + self._binary_file.write(self._database) |
10 | 46 |
|
11 | | - self._database[self._col_name] = [] |
12 | | - # self._collection = list(self._database[self._col_name]) |
13 | | - |
14 | | - def insert(self, doc: dict) -> None: |
15 | | - _doc = doc |
16 | | - print(_doc) |
17 | | - print(self._database) |
18 | | - # data = list(self._collection).append(doc) |
19 | | - data = self._database[self._col_name].append(_doc) |
20 | | - print(self._database) |
21 | | - with open(f"{self._db_name}.json", "w") as f: |
22 | | - json.dump(self._database, f, indent=4) |
23 | 47 |
|
0 commit comments