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