]> git.giorgioravera.it Git - network-manager.git/commitdiff
minor changes to db management
authorGiorgio Ravera <giorgio.ravera@gmail.com>
Fri, 29 May 2026 21:17:58 +0000 (23:17 +0200)
committerGiorgio Ravera <giorgio.ravera@gmail.com>
Fri, 29 May 2026 21:17:58 +0000 (23:17 +0200)
backend/bootstrap.py
backend/db/db.py

index d2683be40b95fd42d8780076371e640d82ef10df..594c68ec43beec6dc33888586b88fbdfe1a3c4b5 100644 (file)
@@ -77,7 +77,7 @@ def bootstrap():
     # Set Database
     configure_db(settings.DB_FILE)
     # Create or update database
-    created = create_db(settings.DB_FILE, settings.DB_RESET)
+    created = create_db(settings.DB_RESET)
 
     # Log Setup
     setup_logging(
index 629043553ee306077e8b33b43e5fca9aade75b12..8d79c375a57aafbcbc651110292ca15522af9e00 100644 (file)
@@ -19,36 +19,53 @@ def register_init(func):
 # Configure database (path)
 # -----------------------------
 def configure_db(path: Path):
-    global _db_path
+    global _db_path, _connection
+
+    if _connection is not None:
+        raise RuntimeError("Database already initialized")
+
     _db_path = path
 
+
 # -----------------------------
 # Init Database
 # -----------------------------
 def init_db():
-
     conn = get_db()
     cur = conn.cursor()
 
-    for func in _init_functions:
+    for func in sorted(_init_functions, key=lambda f: f.__name__):
         func(cur)
 
     conn.commit()
 
 # -----------------------------
-# Init Database
+# Create Database
 # -----------------------------
-def create_db(db_path: Path, reset: bool = False):
-    if reset and db_path.exists():
-        db_path.unlink()
+def create_db(reset: bool = False):
+    global _connection
+
+    if _db_path is None:
+        raise RuntimeError("Database not configured. Call configure_db() first.")
+
+    if reset:
+        if _connection is not None:
+            _connection.close()
+            _connection = None
+
+        if _db_path.exists():
+            _db_path.unlink()
 
-    created = not db_path.exists()
+    # check if db exists
+    existed_before = _db_path.exists()
 
-    db_path.parent.mkdir(parents=True, exist_ok=True)
+    # ensure connection (creates DB file if missing)
+    get_db()
 
+    # ensure schema
     init_db()
 
-    return created
+    return not existed_before
 
 # -----------------------------
 # Connect to the database