Represents a database manager for storing and retrieving items in the expense tracker app. This class provides methods to interact with the underlying database, including inserting, updating, and querying items.
| 217 | |
| 218 | |
| 219 | class ItemsDB: |
| 220 | """ |
| 221 | Represents a database manager for storing and retrieving items in the expense tracker app. |
| 222 | |
| 223 | This class provides methods to interact with the underlying database, including inserting, updating, |
| 224 | and querying items. |
| 225 | """ |
| 226 | |
| 227 | def __init__(self, db_path: str): |
| 228 | """ |
| 229 | Initializes the ItemsDB instance with the provided database file path. |
| 230 | |
| 231 | Args: |
| 232 | db_path (str): The path to the database file. |
| 233 | """ |
| 234 | self.db_path = db_path |
| 235 | |
| 236 | def __len__(self): |
| 237 | """ |
| 238 | Returns the number of items in the database. |
| 239 | |
| 240 | Returns: |
| 241 | int: The number of items in the database. |
| 242 | """ |
| 243 | with TinyDB(self.db_path) as db: |
| 244 | return len(db) |
| 245 | |
| 246 | def print_db(self): |
| 247 | """ |
| 248 | Prints all items in the database as JSON strings. |
| 249 | """ |
| 250 | |
| 251 | for item in self.get_all_items(): |
| 252 | print(item.to_json_str(indent=4)) |
| 253 | |
| 254 | def insert_item(self, item: Item) -> None: |
| 255 | """ |
| 256 | Inserts a single item into the database. |
| 257 | |
| 258 | Args: |
| 259 | item (Item): The item to insert into the database. |
| 260 | """ |
| 261 | |
| 262 | data_dict = dict(json.loads(item.to_json_str())) |
| 263 | with TinyDB(self.db_path) as db: |
| 264 | db.insert(data_dict) |
| 265 | |
| 266 | def insert_items(self, items: List[Item]) -> None: |
| 267 | """ |
| 268 | Inserts multiple items into the database. |
| 269 | |
| 270 | Args: |
| 271 | items (List[Item]): The list of items to insert into the database. |
| 272 | """ |
| 273 | with TinyDB(self.db_path) as db: |
| 274 | db.insert_multiple([dict(json.loads(item.to_json_str())) for item in items]) |
| 275 | |
| 276 | def update_items(self, update_dict: dict, query: Query) -> None: |