1 """Attributes whose values are recorded as a timestamped history."""
2 from datetime import datetime
4 from sqlite3 import Row
6 from plomtask.db import DatabaseConnection
7 from plomtask.exceptions import HandledException, BadFormatException
9 TIMESTAMP_FMT = '%Y-%m-%d %H:%M:%S.%f'
12 class VersionedAttribute:
13 """Attributes whose values are recorded as a timestamped history."""
16 parent: Any, table_name: str, default: str | float) -> None:
18 self.table_name = table_name
19 self.default = default
20 self.history: dict[str, str | float] = {}
22 def __hash__(self) -> int:
23 history_tuples = tuple((k, v) for k, v in self.history.items())
24 hashable = (self.parent.id_, self.table_name, self.default,
29 def _newest_timestamp(self) -> str:
30 """Return most recent timestamp."""
31 return sorted(self.history.keys())[-1]
34 def newest(self) -> str | float:
35 """Return most recent value, or self.default if self.history empty."""
36 if 0 == len(self.history):
38 return self.history[self._newest_timestamp]
40 def reset_timestamp(self, old_str: str, new_str: str) -> None:
41 """Rename self.history key (timestamp) old to new.
43 Chronological sequence of keys must be preserved, i.e. cannot move
44 key before earlier or after later timestamp.
47 new = datetime.strptime(new_str, TIMESTAMP_FMT)
48 old = datetime.strptime(old_str, TIMESTAMP_FMT)
49 except ValueError as exc:
50 raise BadFormatException('Timestamp of illegal format.') from exc
51 timestamps = list(self.history.keys())
52 if old_str not in timestamps:
53 raise HandledException(f'Timestamp {old} not found in history.')
54 sorted_timestamps = sorted([datetime.strptime(t, TIMESTAMP_FMT)
56 expected_position = sorted_timestamps.index(old)
57 sorted_timestamps.remove(old)
58 sorted_timestamps += [new]
59 sorted_timestamps.sort()
60 if sorted_timestamps.index(new) != expected_position:
61 raise HandledException('Timestamp not respecting chronology.')
62 value = self.history[old_str]
63 del self.history[old_str]
64 self.history[new_str] = value
66 def set(self, value: str | float) -> None:
67 """Add to self.history if and only if not same value as newest one.
69 Note that we wait one micro-second, as timestamp comparison to check
70 most recent elements only goes up to that precision.
72 Also note that we don't check against .newest because that may make us
73 compare value against .default even if not set. We want to be able to
74 explicitly set .default as the first element.
77 if 0 == len(self.history) \
78 or value != self.history[self._newest_timestamp]:
79 self.history[datetime.now().strftime(TIMESTAMP_FMT)] = value
81 def history_from_row(self, row: Row) -> None:
82 """Extend self.history from expected table row format."""
83 self.history[row[1]] = row[2]
85 def at(self, queried_time: str) -> str | float:
86 """Retrieve value of timestamp nearest queried_time from the past."""
87 if len(queried_time) == 10:
88 queried_time += ' 23:59:59.999'
89 sorted_timestamps = sorted(self.history.keys())
90 if 0 == len(sorted_timestamps):
92 selected_timestamp = sorted_timestamps[0]
93 for timestamp in sorted_timestamps[1:]:
94 if timestamp > queried_time:
96 selected_timestamp = timestamp
97 return self.history[selected_timestamp]
99 def save(self, db_conn: DatabaseConnection) -> None:
100 """Save as self.history entries, but first wipe old ones."""
101 db_conn.rewrite_relations(self.table_name, 'parent', self.parent.id_,
103 for item in self.history.items()])
105 def remove(self, db_conn: DatabaseConnection) -> None:
106 """Remove from DB."""
107 db_conn.delete_where(self.table_name, 'parent', self.parent.id_)