1 """Collecting Day and date-related items."""
2 from datetime import datetime
3 from sqlite3 import Row
4 from plomtask.misc import HandledException
5 from plomtask.db import DatabaseConnection
7 DATE_FORMAT = '%Y-%m-%d'
10 def date_valid(date: str):
11 """Validate date against DATE_FORMAT, return Datetime or None."""
13 result = datetime.strptime(date, DATE_FORMAT)
14 except (ValueError, TypeError):
20 """Individual days defined by their dates."""
22 def __init__(self, date: str, comment: str = ''):
24 self.datetime = date_valid(self.date)
26 raise HandledException(f'Given date of wrong format: {self.date}')
27 self.comment = comment
29 def __eq__(self, other: object):
30 return isinstance(other, self.__class__) and self.date == other.date
32 def __lt__(self, other):
33 return self.date < other.date
36 def from_table_row(cls, row: Row):
37 """Make new Day from database row."""
38 return cls(row[0], row[1])
41 def all(cls, db_conn: DatabaseConnection,
42 date_range: tuple[str, str] = ('', '')):
43 """Return list of Days in database within date_range."""
44 start_date = date_range[0] if date_range[0] else '2024-01-01'
45 end_date = date_range[1] if date_range[1] else '2030-12-31'
47 sql = 'SELECT * FROM days WHERE date >= ? AND date <= ?'
48 for row in db_conn.exec(sql, (start_date, end_date)):
49 days += [cls.from_table_row(row)]
54 def by_date(cls, db_conn: DatabaseConnection,
55 date: str, create: bool = False):
56 """Retrieve Day by date if in DB, else return None."""
57 for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)):
58 return cls.from_table_row(row)
65 """Return what weekday matches self.date."""
66 return self.datetime.strftime('%A')
68 def save(self, db_conn: DatabaseConnection):
69 """Add (or re-write) self to database."""
70 db_conn.exec('REPLACE INTO days VALUES (?, ?)',
71 (self.date, self.comment))