"""Where a database keeps its data between runs.""" from __future__ import annotations import copy import json import os from typing import Any, Dict, Optional from .errors import MiniDBError class MemoryStorage: """Keeps the data in the process; useful for tests and scratch work.""" def __init__(self) -> None: self._data: Optional[Dict[str, Any]] = None def load(self) -> Optional[Dict[str, Any]]: return copy.deepcopy(self._data) def save(self, data: Dict[str, Any]) -> None: self._data = copy.deepcopy(data) class JsonFileStorage: """Stores the whole database as one JSON document.""" def __init__(self, path: str) -> None: self.path = path def load(self) -> Optional[Dict[str, Any]]: if not os.path.exists(self.path): return None with open(self.path, "r", encoding="utf-8") as handle: try: return json.load(handle) except json.JSONDecodeError as exc: raise MiniDBError("%s is not a valid database file: %s" % (self.path, exc)) from None def save(self, data: Dict[str, Any]) -> None: """Write the data to a temporary file first so that a crash cannot truncate the database.""" temporary = self.path + ".tmp" with open(temporary, "w", encoding="utf-8") as handle: json.dump(data, handle, indent=2) handle.write("\n") os.replace(temporary, self.path)