home · contact · privacy
Cache DB objects to ensure we do not accidentally edit clones.
[plomtask] / plomtask / days.py
index 3b81a7f3bf526fd7bc56849558fbfaa451cdbe88..abfce06f51fc7ab43607ccd177dddc2194667391 100644 (file)
@@ -2,7 +2,7 @@
 from __future__ import annotations
 from datetime import datetime, timedelta
 from sqlite3 import Row
-from plomtask.misc import HandledException
+from plomtask.exceptions import BadFormatException, NotFoundException
 from plomtask.db import DatabaseConnection
 
 DATE_FORMAT = '%Y-%m-%d'
@@ -16,7 +16,7 @@ def valid_date(date_str: str) -> str:
         dt = datetime.strptime(date_str, DATE_FORMAT)
     except (ValueError, TypeError) as e:
         msg = f'Given date of wrong format: {date_str}'
-        raise HandledException(msg) from e
+        raise BadFormatException(msg) from e
     return dt.strftime(DATE_FORMAT)
 
 
@@ -40,9 +40,11 @@ class Day:
         return self.date < other.date
 
     @classmethod
-    def from_table_row(cls, row: Row) -> Day:
-        """Make Day from database row."""
-        return cls(row[0], row[1])
+    def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Day:
+        """Make Day from database row, write to cache."""
+        day = cls(row[0], row[1])
+        db_conn.cached_days[day.date] = day
+        return day
 
     @classmethod
     def all(cls, db_conn: DatabaseConnection,
@@ -54,9 +56,9 @@ class Day:
         start_date = valid_date(date_range[0] if date_range[0] else min_date)
         end_date = valid_date(date_range[1] if date_range[1] else max_date)
         days = []
-        sql = 'SELECT * FROM days WHERE date >= ? AND date <= ?'
+        sql = 'SELECT date FROM days WHERE date >= ? AND date <= ?'
         for row in db_conn.exec(sql, (start_date, end_date)):
-            days += [cls.from_table_row(row)]
+            days += [cls.by_date(db_conn, row[0])]
         days.sort()
         if fill_gaps and len(days) > 1:
             gapless_days = []
@@ -72,12 +74,19 @@ class Day:
     @classmethod
     def by_date(cls, db_conn: DatabaseConnection,
                 date: str, create: bool = False) -> Day:
-        """Retrieve Day by date if in DB, else return None."""
+        """Retrieve Day by date if in DB (prefer cache), else return None."""
+        if date in db_conn.cached_days.keys():
+            day = db_conn.cached_days[date]
+            assert isinstance(day, Day)
+            return day
         for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
-            return cls.from_table_row(row)
+            return cls.from_table_row(db_conn, row)
         if not create:
-            raise HandledException(f'Day not found for date: {date}')
-        return cls(date)
+            raise NotFoundException(f'Day not found for date: {date}')
+        day = cls(date)
+        db_conn.cached_days[date] = day
+        assert isinstance(day, Day)
+        return day
 
     @property
     def weekday(self) -> str:
@@ -97,6 +106,7 @@ class Day:
         return next_datetime.strftime(DATE_FORMAT)
 
     def save(self, db_conn: DatabaseConnection) -> None:
-        """Add (or re-write) self to database."""
+        """Add (or re-write) self to DB and cache."""
         db_conn.exec('REPLACE INTO days VALUES (?, ?)',
                      (self.date, self.comment))
+        db_conn.cached_days[self.date] = self