home · contact · privacy
To DB schema validation error message add diff of offending lines.
[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
5 from plomtask.misc import HandledException
6
7 PATH_DB_SCHEMA = 'scripts/init.sql'
8
9
10 class DatabaseFile:
11     """Represents the sqlite3 database's file."""
12
13     def __init__(self, path):
14         self.path = path
15         self.check()
16
17     def check(self):
18         """Check file exists and is of proper schema."""
19         self.exists = isfile(self.path)
20         if self.exists:
21             self.validate_schema()
22
23     def remake(self):
24         """Create tables in self.path file as per PATH_DB_SCHEMA sql file."""
25         with sql_connect(self.path) as conn:
26             with open(PATH_DB_SCHEMA, 'r', encoding='utf-8') as f:
27                 conn.executescript(f.read())
28         self.check()
29
30     def validate_schema(self):
31         """Compare found schema with what's stored at PATH_DB_SCHEMA."""
32         sql_for_schema = 'SELECT sql FROM sqlite_master ORDER BY sql'
33         msg_err = 'Database has wrong tables schema. Diff:\n'
34         with sql_connect(self.path) as conn:
35             schema_rows = [r[0] for r in conn.execute(sql_for_schema) if r[0]]
36             retrieved_schema = ';\n'.join(schema_rows) + ';'
37             with open(PATH_DB_SCHEMA, 'r', encoding='utf-8') as f:
38                 stored_schema = f.read().rstrip()
39                 if stored_schema != retrieved_schema:
40                     diff_msg = Differ().compare(retrieved_schema.splitlines(),
41                                                 stored_schema.splitlines())
42                     raise HandledException(msg_err + '\n'.join(diff_msg))