1 """Database management."""
2 from os.path import isfile
3 from difflib import Differ
4 from sqlite3 import connect as sql_connect, Cursor
6 from plomtask.exceptions import HandledException
8 PATH_DB_SCHEMA = 'scripts/init.sql'
11 class DatabaseFile: # pylint: disable=too-few-public-methods
12 """Represents the sqlite3 database's file."""
14 def __init__(self, path: str) -> None:
18 def remake(self) -> None:
19 """Create tables in self.path file as per PATH_DB_SCHEMA sql file."""
20 with sql_connect(self.path) as conn:
21 with open(PATH_DB_SCHEMA, 'r', encoding='utf-8') as f:
22 conn.executescript(f.read())
25 def _check(self) -> None:
26 """Check file exists and is of proper schema."""
27 self.exists = isfile(self.path)
29 self._validate_schema()
31 def _validate_schema(self) -> None:
32 """Compare found schema with what's stored at PATH_DB_SCHEMA."""
33 sql_for_schema = 'SELECT sql FROM sqlite_master ORDER BY sql'
34 msg_err = 'Database has wrong tables schema. Diff:\n'
35 with sql_connect(self.path) as conn:
36 schema_rows = [r[0] for r in conn.execute(sql_for_schema) if r[0]]
37 retrieved_schema = ';\n'.join(schema_rows) + ';'
38 with open(PATH_DB_SCHEMA, 'r', encoding='utf-8') as f:
39 stored_schema = f.read().rstrip()
40 if stored_schema != retrieved_schema:
41 diff_msg = Differ().compare(retrieved_schema.splitlines(),
42 stored_schema.splitlines())
43 raise HandledException(msg_err + '\n'.join(diff_msg))
46 class DatabaseConnection:
47 """A single connection to the database."""
49 def __init__(self, db_file: DatabaseFile) -> None:
51 self.conn = sql_connect(self.file.path)
53 def commit(self) -> None:
54 """Commit SQL transaction."""
57 def exec(self, code: str, inputs: tuple[Any, ...] = tuple()) -> Cursor:
58 """Add commands to SQL transaction."""
59 return self.conn.execute(code, inputs)
61 def close(self) -> None:
62 """Close DB connection."""