home · contact · privacy
dd2ee2452a7480878c47b38f2669c08cee229ca6
[plomtask] / plomtask / db.py
1 """Database management."""
2 from os.path import isfile
3 from difflib import Differ
4 from sqlite3 import connect as sql_connect, Cursor, Row
5 from typing import Any, Dict
6 from plomtask.exceptions import HandledException
7
8 PATH_DB_SCHEMA = 'scripts/init.sql'
9 EXPECTED_DB_VERSION = 0
10
11
12 class DatabaseFile:  # pylint: disable=too-few-public-methods
13     """Represents the sqlite3 database's file."""
14
15     def __init__(self, path: str) -> None:
16         self.path = path
17         self._check()
18
19     def remake(self) -> None:
20         """Create tables in self.path file as per PATH_DB_SCHEMA sql file."""
21         with sql_connect(self.path) as conn:
22             with open(PATH_DB_SCHEMA, 'r', encoding='utf-8') as f:
23                 conn.executescript(f.read())
24         self._check()
25
26     def _check(self) -> None:
27         """Check file exists, and is of proper DB version and schema."""
28         self.exists = isfile(self.path)
29         if self.exists:
30             self._validate_user_version()
31             self._validate_schema()
32
33     def _validate_user_version(self) -> None:
34         """Compare DB user_version with EXPECTED_DB_VERSION."""
35         sql_for_db_version = 'PRAGMA user_version'
36         with sql_connect(self.path) as conn:
37             db_version = list(conn.execute(sql_for_db_version))[0][0]
38             if db_version != EXPECTED_DB_VERSION:
39                 msg = f'Wrong DB version, expected '\
40                         f'{EXPECTED_DB_VERSION}, got {db_version}.'
41                 raise HandledException(msg)
42
43     def _validate_schema(self) -> None:
44         """Compare found schema with what's stored at PATH_DB_SCHEMA."""
45         sql_for_schema = 'SELECT sql FROM sqlite_master ORDER BY sql'
46         msg_err = 'Database has wrong tables schema. Diff:\n'
47         with sql_connect(self.path) as conn:
48             schema_rows = [r[0] for r in conn.execute(sql_for_schema) if r[0]]
49             retrieved_schema = ';\n'.join(schema_rows) + ';'
50             with open(PATH_DB_SCHEMA, 'r', encoding='utf-8') as f:
51                 stored_schema = f.read().rstrip()
52                 if stored_schema != retrieved_schema:
53                     diff_msg = Differ().compare(retrieved_schema.splitlines(),
54                                                 stored_schema.splitlines())
55                     raise HandledException(msg_err + '\n'.join(diff_msg))
56
57
58 class DatabaseConnection:
59     """A single connection to the database."""
60
61     def __init__(self, db_file: DatabaseFile) -> None:
62         self.file = db_file
63         self.conn = sql_connect(self.file.path)
64         self.cached_todos: Dict[int, Any] = {}
65         self.cached_days: Dict[str, Any] = {}
66         self.cached_process_steps: Dict[int, Any] = {}
67         self.cached_processes: Dict[int, Any] = {}
68         self.cached_conditions: Dict[int, Any] = {}
69
70     def commit(self) -> None:
71         """Commit SQL transaction."""
72         self.conn.commit()
73
74     def exec(self, code: str, inputs: tuple[Any, ...] = tuple()) -> Cursor:
75         """Add commands to SQL transaction."""
76         return self.conn.execute(code, inputs)
77
78     def close(self) -> None:
79         """Close DB connection."""
80         self.conn.close()
81
82     def rewrite_relations(self, table_name: str, key: str, target: int,
83                           rows: list[list[Any]]) -> None:
84         """Rewrite relations in table_name to target, with rows values."""
85         self.delete_where(table_name, key, target)
86         for row in rows:
87             values = tuple([target] + row)
88             q_marks = self.__class__.q_marks_from_values(values)
89             self.exec(f'INSERT INTO {table_name} VALUES {q_marks}', values)
90
91     def row_where(self, table_name: str, key: str,
92                   target: int | str) -> list[Row]:
93         """Return list of Rows at table where key == target."""
94         return list(self.exec(f'SELECT * FROM {table_name} WHERE {key} = ?',
95                               (target,)))
96
97     def column_where(self, table_name: str, column: str, key: str,
98                      target: int | str) -> list[Any]:
99         """Return column of table where key == target."""
100         return [row[0] for row in
101                 self.exec(f'SELECT {column} FROM {table_name} '
102                           f'WHERE {key} = ?', (target,))]
103
104     def column_all(self, table_name: str, column: str) -> list[Any]:
105         """Return complete column of table."""
106         return [row[0] for row in
107                 self.exec(f'SELECT {column} FROM {table_name}')]
108
109     def delete_where(self, table_name: str, key: str, target: int) -> None:
110         """Delete from table where key == target."""
111         self.exec(f'DELETE FROM {table_name} WHERE {key} = ?', (target,))
112
113     @staticmethod
114     def q_marks_from_values(values: tuple[Any]) -> str:
115         """Return placeholder to insert values into SQL code."""
116         return '(' + ','.join(['?'] * len(values)) + ')'
117
118
119 class BaseModel:
120     """Template for most of the models we use/derive from the DB."""
121     table_name = ''
122     to_save: list[str] = []
123     id_: None | int | str
124     id_type: type[Any] = int
125
126     @classmethod
127     def from_table_row(cls, db_conn: DatabaseConnection,
128                        row: Row | list[Any]) -> Any:
129         """Make from DB row, write to DB cache."""
130         obj = cls(*row)
131         assert isinstance(obj.id_, cls.id_type)
132         cache = getattr(db_conn, f'cached_{cls.table_name}')
133         cache[obj.id_] = obj
134         return obj
135
136     @classmethod
137     def _by_id(cls,
138                db_conn: DatabaseConnection,
139                id_: int | str) -> tuple[Any, bool]:
140         """Return instance found by ID, or None, and if from cache or not."""
141         from_cache = False
142         obj = None
143         cache = getattr(db_conn, f'cached_{cls.table_name}')
144         if id_ in cache.keys():
145             obj = cache[id_]
146             from_cache = True
147         else:
148             for row in db_conn.row_where(cls.table_name, 'id', id_):
149                 obj = cls.from_table_row(db_conn, row)
150                 cache[id_] = obj
151                 break
152         return obj, from_cache
153
154     def set_int_id(self, id_: int | None) -> None:
155         """Set id_ if >= 1 or None, else fail."""
156         if (id_ is not None) and id_ < 1:
157             msg = f'illegal {self.__class__.__name__} ID, must be >=1: {id_}'
158             raise HandledException(msg)
159         self.id_ = id_
160
161     def save_core(self, db_conn: DatabaseConnection,
162                   update_with_lastrowid: bool = True) -> None:
163         """Write bare-bones self (sans connected items), ensuring self.id_."""
164         values = tuple([self.id_] + [getattr(self, key)
165                                      for key in self.to_save])
166         q_marks = DatabaseConnection.q_marks_from_values(values)
167         table_name = self.table_name
168         cursor = db_conn.exec(f'REPLACE INTO {table_name} VALUES {q_marks}',
169                               values)
170         if update_with_lastrowid:
171             self.id_ = cursor.lastrowid
172         cache = getattr(db_conn, f'cached_{table_name}')
173         cache[self.id_] = self