home · contact · privacy
Cache DB objects to ensure we do not accidentally edit clones.
[plomtask] / plomtask / days.py
1 """Collecting Day and date-related items."""
2 from __future__ import annotations
3 from datetime import datetime, timedelta
4 from sqlite3 import Row
5 from plomtask.exceptions import BadFormatException, NotFoundException
6 from plomtask.db import DatabaseConnection
7
8 DATE_FORMAT = '%Y-%m-%d'
9
10
11 def valid_date(date_str: str) -> str:
12     """Validate date against DATE_FORMAT or 'today', return in DATE_FORMAT."""
13     if date_str == 'today':
14         date_str = todays_date()
15     try:
16         dt = datetime.strptime(date_str, DATE_FORMAT)
17     except (ValueError, TypeError) as e:
18         msg = f'Given date of wrong format: {date_str}'
19         raise BadFormatException(msg) from e
20     return dt.strftime(DATE_FORMAT)
21
22
23 def todays_date() -> str:
24     """Return current date in DATE_FORMAT."""
25     return datetime.now().strftime(DATE_FORMAT)
26
27
28 class Day:
29     """Individual days defined by their dates."""
30
31     def __init__(self, date: str, comment: str = '') -> None:
32         self.date = valid_date(date)
33         self.datetime = datetime.strptime(self.date, DATE_FORMAT)
34         self.comment = comment
35
36     def __eq__(self, other: object) -> bool:
37         return isinstance(other, self.__class__) and self.date == other.date
38
39     def __lt__(self, other: Day) -> bool:
40         return self.date < other.date
41
42     @classmethod
43     def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Day:
44         """Make Day from database row, write to cache."""
45         day = cls(row[0], row[1])
46         db_conn.cached_days[day.date] = day
47         return day
48
49     @classmethod
50     def all(cls, db_conn: DatabaseConnection,
51             date_range: tuple[str, str] = ('', ''),
52             fill_gaps: bool = False) -> list[Day]:
53         """Return list of Days in database within date_range."""
54         min_date = '2024-01-01'
55         max_date = '2030-12-31'
56         start_date = valid_date(date_range[0] if date_range[0] else min_date)
57         end_date = valid_date(date_range[1] if date_range[1] else max_date)
58         days = []
59         sql = 'SELECT date FROM days WHERE date >= ? AND date <= ?'
60         for row in db_conn.exec(sql, (start_date, end_date)):
61             days += [cls.by_date(db_conn, row[0])]
62         days.sort()
63         if fill_gaps and len(days) > 1:
64             gapless_days = []
65             for i, day in enumerate(days):
66                 gapless_days += [day]
67                 if i < len(days) - 1:
68                     while day.next_date != days[i+1].date:
69                         day = Day(day.next_date)
70                         gapless_days += [day]
71             days = gapless_days
72         return days
73
74     @classmethod
75     def by_date(cls, db_conn: DatabaseConnection,
76                 date: str, create: bool = False) -> Day:
77         """Retrieve Day by date if in DB (prefer cache), else return None."""
78         if date in db_conn.cached_days.keys():
79             day = db_conn.cached_days[date]
80             assert isinstance(day, Day)
81             return day
82         for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
83             return cls.from_table_row(db_conn, row)
84         if not create:
85             raise NotFoundException(f'Day not found for date: {date}')
86         day = cls(date)
87         db_conn.cached_days[date] = day
88         assert isinstance(day, Day)
89         return day
90
91     @property
92     def weekday(self) -> str:
93         """Return what weekday matches self.date."""
94         return self.datetime.strftime('%A')
95
96     @property
97     def prev_date(self) -> str:
98         """Return date preceding date of this Day."""
99         prev_datetime = self.datetime - timedelta(days=1)
100         return prev_datetime.strftime(DATE_FORMAT)
101
102     @property
103     def next_date(self) -> str:
104         """Return date succeeding date of this Day."""
105         next_datetime = self.datetime + timedelta(days=1)
106         return next_datetime.strftime(DATE_FORMAT)
107
108     def save(self, db_conn: DatabaseConnection) -> None:
109         """Add (or re-write) self to DB and cache."""
110         db_conn.exec('REPLACE INTO days VALUES (?, ?)',
111                      (self.date, self.comment))
112         db_conn.cached_days[self.date] = self