All database operations work with an in-memory data structure (dict[str, Any]) that can be persisted to disk. The database tracks changes using an internal _dirty flag to know when data needs to be committed.
Keys must be strings (not integers, bytes, or other types)
Keys cannot be empty strings
Violating these rules raises KeyValidationError
database.py:65-70
def _validate_key(self, key: str) -> None: if not isinstance(key, str): raise KeyValidationError("Database keys must be strings") if not key: raise KeyValidationError("Database keys cannot be empty")
db = Database("mydata.pkl")db.load()# Get existing valueusername = db.get("username") # Returns "alice"# Get with default valueage = db.get("age", 25) # Returns 25 if "age" doesn't exist# Returns None if key doesn't exist and no default providedmissing = db.get("nonexistent") # Returns None
Method Signature:
database.py:94-101
def get(self, key: str, default: Any = None) -> Any: """ Retrieve a record by key. """ self._ensure_open() self._validate_key(key) return self._data.get(key, default)
Update specific fields of a dictionary record without replacing the entire value.
db = Database("mydata.pkl")# Store a dictionarydb.set("user", { "name": "Alice", "email": "[email protected]", "age": 30})# Update only specific fieldsdb.update("user", {"age": 31, "city": "New York"})# Result: {"name": "Alice", "email": "[email protected]", "age": 31, "city": "New York"}
Method Signature:
database.py:114-132
def update(self, key: str, changes: dict[str, Any]) -> None: """ Update fields of a dictionary record. Raises: RecordTypeError: If the stored value is not a dict. """ self._ensure_open() self._validate_key(key) if key not in self._data: raise KeyError(f"Key '{key}' not found") record = self._data[key] if not isinstance(record, dict): raise RecordTypeError("Cannot update non-dictionary record") record.update(changes) self._mark_dirty()
update() only works with dictionary values. Attempting to update a non-dict value raises RecordTypeError.
Error Handling:
db.set("score", 100) # Not a dictionarytry: db.update("score", {"points": 150})except RecordTypeError as e: print(f"Error: {e}") # "Cannot update non-dictionary record"
db = Database("mydata.pkl")db.set("temp_data", "value")# Delete the keydb.delete("temp_data")# Safe to delete non-existent keys (no error)db.delete("nonexistent") # Does nothing
Method Signature:
database.py:103-112
def delete(self, key: str) -> None: """ Delete a record if it exists. """ self._ensure_open() self._validate_key(key) if key in self._data: del self._data[key] self._mark_dirty()
Deleting a non-existent key is a no-op (does not raise an error).