From 01500fc0200eec13184c93b64d57281e11207dc6 Mon Sep 17 00:00:00 2001
From: Christian Heller <c.heller@plomlompom.de>
Date: Mon, 6 Jan 2025 17:40:56 +0100
Subject: [PATCH] Don't commit migrations before surviving schema validation of
 end result.

---
 src/ytplom/db.py | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)

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()
 
 
-- 
2.30.2