X-Git-Url: https://plomlompom.com/repos/?a=blobdiff_plain;f=plomtask%2Fdays.py;h=abfce06f51fc7ab43607ccd177dddc2194667391;hb=6b329a28bb4aec8d1846f5cc5402ed6fca5eb3da;hp=afdea33760b41df3149c857b306c6e2b447b7df8;hpb=982d712cbf12acde21ce448e0d1ed28468f1c90e;p=plomtask diff --git a/plomtask/days.py b/plomtask/days.py index afdea33..abfce06 100644 --- a/plomtask/days.py +++ b/plomtask/days.py @@ -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 NotFoundException(f'Day not found for date: {date}') - return cls(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