From 280cd23db7740dc3ce9c31124586eb4f615d15d0 Mon Sep 17 00:00:00 2001 From: Giorgio Ravera Date: Fri, 29 May 2026 23:17:58 +0200 Subject: [PATCH] minor changes to db management --- backend/bootstrap.py | 2 +- backend/db/db.py | 37 +++++++++++++++++++++++++++---------- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/backend/bootstrap.py b/backend/bootstrap.py index d2683be..594c68e 100644 --- a/backend/bootstrap.py +++ b/backend/bootstrap.py @@ -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( diff --git a/backend/db/db.py b/backend/db/db.py index 6290435..8d79c37 100644 --- a/backend/db/db.py +++ b/backend/db/db.py @@ -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 -- 2.47.3