From 694bda3a46a8ffc7c185bd47c5b7bb20889a32ee Mon Sep 17 00:00:00 2001 From: Xoconoch Date: Thu, 7 Aug 2025 20:36:28 -0600 Subject: [PATCH] Ensure db structure is valid before performing tasks --- routes/utils/history_manager.py | 8 ++++++++ routes/utils/watch/db.py | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/routes/utils/history_manager.py b/routes/utils/history_manager.py index 82208f6..16f35d3 100644 --- a/routes/utils/history_manager.py +++ b/routes/utils/history_manager.py @@ -273,6 +273,8 @@ class HistoryManager: track.get("duration_ms", 0) )) else: + # Ensure target children table exists before write + self._create_children_table(table) # Store in children table (for album/playlist tracks) logger.info(f"Storing track '{track.get('title', 'Unknown')}' in CHILDREN table '{table}' for task {task_id}") # Extract ISRC @@ -528,6 +530,8 @@ class HistoryManager: def _populate_album_children_table(self, table_name: str, summary: Dict, album_title: str): """Populate children table with individual track records from album summary.""" try: + # Ensure table exists before population + self._create_children_table(table_name) all_tracks = [] # Add successful tracks @@ -566,6 +570,8 @@ class HistoryManager: def _populate_playlist_children_table(self, table_name: str, summary: Dict): """Populate children table with individual track records from playlist summary.""" try: + # Ensure table exists before population + self._create_children_table(table_name) all_tracks = [] # Add successful tracks @@ -722,6 +728,8 @@ class HistoryManager: List of track records """ try: + # Ensure table exists before reading + self._create_children_table(children_table) with self._get_connection() as conn: cursor = conn.execute(f""" SELECT * FROM {children_table} diff --git a/routes/utils/watch/db.py b/routes/utils/watch/db.py index d89f6a3..0f7bac0 100644 --- a/routes/utils/watch/db.py +++ b/routes/utils/watch/db.py @@ -1408,3 +1408,29 @@ def is_album_in_artist_db(artist_spotify_id: str, album_spotify_id: str) -> bool exc_info=True, ) return False # Assume not present on error + + +# --- Eager module initialization to ensure DBs and core tables exist --- +_initialized_on_import = False + + +def initialize_databases_eagerly() -> None: + """Create DB directory and initialize core tables so they exist before any usage.""" + global _initialized_on_import + if _initialized_on_import: + return + try: + # Ensure base directory exists + DB_DIR.mkdir(parents=True, exist_ok=True) + # Initialize core databases and tables + init_playlists_db() + init_artists_db() + _initialized_on_import = True + logger.info("Eagerly initialized watch databases and core tables.") + except Exception: + # Log and proceed; functions will attempt to (re)initialize as needed + logger.error("Failed to eagerly initialize watch databases.", exc_info=True) + + +# Invoke eager initialization at import time +initialize_databases_eagerly()