From: Christian Heller <c.heller@plomlompom.de>
Date: Mon, 6 Jan 2025 16:40:56 +0000 (+0100)
Subject: Don't commit migrations before surviving schema validation of end result.
X-Git-Url: https://plomlompom.com/repos/%7B%7Bprefix%7D%7D/static/%7B%7B%20web_path%20%7D%7D/day_todos?a=commitdiff_plain;h=01500fc0200eec13184c93b64d57281e11207dc6;p=ytplom

Don't commit migrations before surviving schema validation of end result.
---

diff --git a/src/ytplom/db.py b/src/ytplom/db.py
index 46cd9ab..d96a7ab 100644
--- a/src/ytplom/db.py
+++ b/src/ytplom/db.py
@@ -68,23 +68,20 @@ class DbFile:
         self.path = path
         if not self.path.is_file():
             raise HandledException(f'no DB file at {self.path}')
-
         if version_to_validate < 0:
             return
-        # ensure version
         if (user_version := self._get_user_version()) != version_to_validate:
             raise HandledException(
                 f'wrong DB version {user_version} (!= {version_to_validate})')
+        with DbConn(self) as conn:
+            self._validate_schema(conn)
 
-        # ensure schema
-        with sql_connect(self.path) as conn:
-            schema_rows = [
-                    r[0] for r in
-                    conn.execute('SELECT sql FROM sqlite_master ORDER BY sql')
-                    if r[0]]
+    @staticmethod
+    def _validate_schema(conn: 'DbConn'):
+        schema_sql = SqlText('SELECT sql FROM sqlite_master ORDER BY sql')
         schema_rows_normed = []
         indent = '  '
-        for row in schema_rows:
+        for row in [r[0] for r in conn.exec(schema_sql) if r[0]]:
             row_normed = []
             for subrow in row.split('\n'):
                 subrow = subrow.rstrip()
@@ -152,6 +149,7 @@ class DbFile:
             for migration in DbMigration.from_to_in_set(
                     start_version, EXPECTED_DB_VERSION, migrations):
                 migration.perform(conn)
+            self._validate_schema(conn)
             conn.commit()