From 649ec0c89ef044339af3d744b68233b7da85be4a Mon Sep 17 00:00:00 2001 From: Kalzu Rekku Date: Sat, 5 Apr 2025 22:45:18 +0300 Subject: [PATCH] Small logical mistake on schema applying. --- SlidingSqlite.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/SlidingSqlite.py b/SlidingSqlite.py index 58b6efd..e0e9d4a 100644 --- a/SlidingSqlite.py +++ b/SlidingSqlite.py @@ -187,7 +187,7 @@ class SlidingSQLite: def _get_connection(self, db_file: str) -> sqlite3.Connection: """ Get a connection to the specified database file. - Reuses existing connections when possible. + Reuses existing connections when possible and applies schema only if needed. Args: db_file: Path to the database file @@ -214,8 +214,30 @@ class SlidingSQLite: ) conn.execute("PRAGMA journal_mode=WAL;") conn.execute("PRAGMA busy_timeout=5000;") - if db_file != self._get_metadata_db(): - conn.executescript(self.schema) + + # Only apply schema if the database is new + if db_file != self._get_metadata_db() and os.path.exists(db_file): + # Check if schema is already applied by testing for a known table + try: + conn.execute("SELECT 1 FROM node_auth LIMIT 1") + except sqlite3.Error: + # Schema not applied yet, apply it + try: + conn.executescript(self.schema) + conn.commit() + except sqlite3.Error as e: + logging.error(f"Failed to apply schema to {db_file}: {e}") + conn.close() + raise DatabaseError(f"Failed to apply schema to {db_file}: {e}") + elif db_file != self._get_metadata_db(): + # New file, apply schema + try: + conn.executescript(self.schema) + conn.commit() + except sqlite3.Error as e: + logging.error(f"Failed to apply schema to new {db_file}: {e}") + conn.close() + raise DatabaseError(f"Failed to apply schema to {db_file}: {e}") self.connections[db_file] = conn except sqlite3.Error as e: @@ -262,15 +284,15 @@ class SlidingSQLite: "SELECT id FROM metadata WHERE db_file = ?", (current_db,) ) existing = cursor.fetchone() - if existing: - logging.debug(f"Database {current_db} already registered") - else: + if not existing: conn.execute( "INSERT OR IGNORE INTO metadata (db_file, start_time, end_time) VALUES (?, ?, ?)", (current_db, interval_start, interval_end), ) conn.commit() logging.debug(f"Registered new database: {current_db}") + else: + logging.debug(f"Database {current_db} already registered") except sqlite3.Error as e: logging.error(f"Failed to register current database: {e}") # Continue execution as this is not critical