Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

Fix several issues with DB handling (#573)

Daniel Petti88a020b6376d
diff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.py
index 782d266271..8227f2ae8d 100644
--- a/src/local_deep_research/__init__.py
+++ b/src/local_deep_research/__init__.py
@@ -12,10 +12,16 @@ from .config.llm_config import get_llm
from .config.search_config import get_search
from .report_generator import get_report_generator
from .web.app import main
+from .web.database.migrations import ensure_database_initialized
+from .setup_data_dir import setup_data_dir
# Disable logging by default to not interfere with user setup.
logger.disable("local_deep_research")
+# Initialize database.
+setup_data_dir()
+ensure_database_initialized()
+
def get_advanced_search_system(strategy_name: str = "iterdrag"):
"""
diff --git a/src/local_deep_research/migrate_db.py b/src/local_deep_research/migrate_db.py
deleted file mode 100644
index a2d37b1f67..0000000000
--- a/src/local_deep_research/migrate_db.py
+++ /dev/null
@@ -1,149 +0,0 @@
-#!/usr/bin/env python
-"""
-Database migration script for Local Deep Research.
-Migrates data from legacy databases (deep_research.db and research_history.db) to the new unified database (ldr.db).
-"""
-
-import argparse
-import logging
-import os
-import sys
-
-try:
- from local_deep_research.web.database.migrate_to_ldr_db import (
- migrate_to_ldr_db,
- )
- from local_deep_research.web.models.database import (
- DB_PATH,
- LEGACY_DEEP_RESEARCH_DB,
- LEGACY_RESEARCH_HISTORY_DB,
- )
-except ImportError:
- # If that fails, try with the relative path.
- from .web.database.migrate_to_ldr_db import migrate_to_ldr_db
- from .web.models.database import (
- DB_PATH,
- LEGACY_DEEP_RESEARCH_DB,
- LEGACY_RESEARCH_HISTORY_DB,
- )
-
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
- handlers=[logging.StreamHandler()],
-)
-logger = logging.getLogger("migrate_db")
-
-# Add proper paths for import
-current_dir = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, os.path.dirname(os.path.dirname(current_dir)))
-
-
-def main():
- """Main migration function that parses arguments and runs the migration"""
- parser = argparse.ArgumentParser(
- description="Local Deep Research Database Migration"
- )
- parser.add_argument(
- "--backup",
- action="store_true",
- help="Create backup of existing databases before migration",
- )
- parser.add_argument(
- "--force",
- action="store_true",
- help="Force migration even if target database exists",
- )
- parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Only check what would be migrated, don't perform actual migration",
- )
- parser.add_argument(
- "--verbose", action="store_true", help="Enable verbose logging"
- )
-
- args = parser.parse_args()
-
- if args.verbose:
- logging.getLogger().setLevel(logging.DEBUG)
-
- print("=" * 80)
- print("LOCAL DEEP RESEARCH DATABASE MIGRATION")
- print("=" * 80)
-
- try:
- # First try the normal import
- print(f"Target database will be created at: {DB_PATH}")
-
- # Check if migration is needed
- if os.path.exists(DB_PATH) and not args.force:
- print(f"Target database already exists at: {DB_PATH}")
- if (
- input(
- "Do you want to continue anyway? This may overwrite data. (y/n): "
- ).lower()
- != "y"
- ):
- print("Migration aborted.")
- return 1
-
- # Check if source databases exist
- deep_research_exists = os.path.exists(LEGACY_DEEP_RESEARCH_DB)
- research_history_exists = os.path.exists(LEGACY_RESEARCH_HISTORY_DB)
-
- if not deep_research_exists and not research_history_exists:
- print("No legacy databases found. Nothing to migrate.")
- return 0
-
- print("Found legacy databases:")
- if deep_research_exists:
- print(f" - {LEGACY_DEEP_RESEARCH_DB}")
- if research_history_exists:
- print(f" - {LEGACY_RESEARCH_HISTORY_DB}")
-
- # Create backups if requested
- if args.backup:
- if deep_research_exists:
- backup_path = f"{LEGACY_DEEP_RESEARCH_DB}.bak"
- import shutil
-
- shutil.copy2(LEGACY_DEEP_RESEARCH_DB, backup_path)
- print(f"Created backup: {backup_path}")
-
- if research_history_exists:
- backup_path = f"{LEGACY_RESEARCH_HISTORY_DB}.bak"
- import shutil
-
- shutil.copy2(LEGACY_RESEARCH_HISTORY_DB, backup_path)
- print(f"Created backup: {backup_path}")
-
- # Run migration or dry run
- if args.dry_run:
- print("\nDRY RUN - No changes will be made.")
- print(f"Would migrate data to: {DB_PATH}")
- return 0
- else:
- print(f"\nStarting migration to: {DB_PATH}")
-
- success = migrate_to_ldr_db()
-
- if success:
- print("\nMigration completed successfully.")
- print(
- "You can now start the application with the new unified database."
- )
- return 0
- else:
- print("\nMigration failed. Check the logs for details.")
- return 1
-
- except Exception as e:
- logger.error(f"Migration error: {e}", exc_info=True)
- print(f"Error during migration: {e}")
- return 1
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/src/local_deep_research/setup_data_dir.py b/src/local_deep_research/setup_data_dir.py
index 3b5a470148..e64da2e090 100644
--- a/src/local_deep_research/setup_data_dir.py
+++ b/src/local_deep_research/setup_data_dir.py
@@ -5,6 +5,7 @@ Creates the data directory for the application database if it doesn't exist.
"""
import os
+from loguru import logger
def setup_data_dir():
@@ -19,9 +20,9 @@ def setup_data_dir():
# Create the data directory if it doesn't exist
if not os.path.exists(data_dir):
os.makedirs(data_dir)
- print(f"Created data directory at: {data_dir}")
+ logger.info(f"Created data directory at: {data_dir}")
else:
- print(f"Data directory already exists at: {data_dir}")
+ logger.info(f"Data directory already exists at: {data_dir}")
# Return the path to the data directory
return data_dir
diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.py
index 45b99d6c49..bd62a4d180 100644
--- a/src/local_deep_research/utilities/db_utils.py
+++ b/src/local_deep_research/utilities/db_utils.py
@@ -17,8 +17,13 @@ DB_PATH = os.path.join(DATA_DIR, "ldr.db")
@thread_specific_cache(cache=LRUCache(maxsize=10))
-def get_db_session() -> Session:
+def get_db_session(_namespace: str = "") -> Session:
"""
+ Args:
+ _namespace: This can be specified to an arbitrary string in order to
+ force the caching mechanism to create separate settings even in
+ the same thread. Usually it does not need to be specified.
+
Returns:
The singleton DB session for each thread.
@@ -28,7 +33,6 @@ def get_db_session() -> Session:
return session_class()
-@thread_specific_cache(cache=LRUCache(maxsize=1))
def get_settings_manager() -> SettingsManager:
"""
Returns:
@@ -54,12 +58,9 @@ def get_db_setting(
"""
try:
# Get settings manager which handles database access
- value = get_settings_manager().get_setting(key)
-
- if value is not None:
- return value
+ return get_settings_manager().get_setting(key, default=default_value)
except Exception:
logger.exception(f"Error getting setting {key} from database")
- logger.warning(f"Could not find setting '{key}' in the database.")
+ logger.warning(f"Could not read setting '{key}' from the database.")
return default_value
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.py
index 5862b716d2..826a83fa1d 100644
--- a/src/local_deep_research/utilities/log_utils.py
+++ b/src/local_deep_research/utilities/log_utils.py
@@ -130,7 +130,7 @@ def database_sink(message: loguru.Message) -> None:
)
# Save the entry to the database.
- db_session = get_db_session()
+ db_session = get_db_session("log_utils.database_sink")
try:
db_session.add(db_log)
db_session.commit()
diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.py
index c880a8f699..7e6f289700 100644
--- a/src/local_deep_research/web/api.py
+++ b/src/local_deep_research/web/api.py
@@ -10,7 +10,7 @@ from functools import wraps
from flask import Blueprint, jsonify, request
from ..api.research_functions import analyze_documents
-from .services.settings_service import get_setting
+from ..utilities.db_utils import get_db_setting
# Create a blueprint for the API
api_blueprint = Blueprint("api_v1", __name__, url_prefix="/api/v1")
@@ -30,12 +30,14 @@ def api_access_control(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# Check if API is enabled
- api_enabled = get_setting("app.enable_api", True) # Default to enabled
+ api_enabled = get_db_setting(
+ "app.enable_api", True
+ ) # Default to enabled
if not api_enabled:
return jsonify({"error": "API access is disabled"}), 403
# Implement rate limiting
- rate_limit = get_setting(
+ rate_limit = get_db_setting(
"app.api_rate_limit", 60
) # Default 60 requests per minute
if rate_limit:
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 7423c04556..c47b648002 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -1,49 +1,8 @@
-import os
-import sys
-
from loguru import logger
-from ..setup_data_dir import setup_data_dir
from ..utilities.db_utils import get_db_setting
from ..utilities.log_utils import config_logger
from .app_factory import create_app
-from .models.database import (
- DB_PATH,
- LEGACY_DEEP_RESEARCH_DB,
- LEGACY_RESEARCH_HISTORY_DB,
-)
-
-# Ensure data directory exists
-setup_data_dir()
-
-# Run schema upgrades if database exists
-if os.path.exists(DB_PATH):
- try:
- logger.info("Running schema upgrades on existing database")
- from .database.schema_upgrade import run_schema_upgrades
-
- run_schema_upgrades()
- except Exception:
- logger.exception("Error running schema upgrades")
- logger.warning("Continuing without schema upgrades")
-
-
-# Check if we need to run database migration
-def check_migration_needed():
- """Check if database migration is needed, based on presence of legacy files and absence of new DB"""
- if not os.path.exists(DB_PATH):
- # The new database doesn't exist, check if legacy databases exist
- legacy_files_exist = os.path.exists(
- LEGACY_DEEP_RESEARCH_DB
- ) or os.path.exists(LEGACY_RESEARCH_HISTORY_DB)
-
- if legacy_files_exist:
- logger.info(
- "Legacy database files found, but ldr.db doesn't exist. Migration needed."
- )
- return True
-
- return False
@logger.catch
@@ -58,39 +17,6 @@ def main():
# Create the Flask app and SocketIO instance
app, socketio = create_app()
- # Check if migration is needed
- if check_migration_needed():
- logger.info(
- "Database migration required. Run migrate_db.py before starting the application."
- )
- print("=" * 80)
- print("DATABASE MIGRATION REQUIRED")
- print(
- "Legacy database files were found, but the new unified database doesn't exist."
- )
- print(
- "Please run 'python -m src.local_deep_research.web.database.migrate_to_ldr_db' to migrate your data."
- )
- print(
- "You can continue without migration, but your previous data won't be available."
- )
- print("=" * 80)
-
- # If --auto-migrate flag is passed, run migration automatically
- if "--auto-migrate" in sys.argv:
- logger.info("Auto-migration flag detected, running migration...")
- try:
- from .database.migrate_to_ldr_db import migrate_to_ldr_db
-
- success = migrate_to_ldr_db()
- if success:
- logger.info("Database migration completed successfully.")
- else:
- logger.warning("Database migration failed.")
- except Exception:
- logger.exception("Error running database migration")
- print("Please run migration manually.")
-
# Get web server settings with defaults
port = get_db_setting("web.port", 5000)
host = get_db_setting("web.host", "0.0.0.0")
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 9dae4db2d1..55b68594df 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -13,7 +13,7 @@ from flask_wtf.csrf import CSRFProtect
from loguru import logger
from ..utilities.log_utils import InterceptHandler
-from .models.database import DB_PATH, init_db
+from .models.database import DB_PATH
from .services.socket_service import SocketIOService
@@ -77,7 +77,6 @@ def create_app():
# Initialize the database
create_database(app)
- init_db()
# Register socket service
socket_service = SocketIOService(app=app)
@@ -261,9 +260,6 @@ def create_database(app):
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
- from .database.migrations import run_migrations
- from .database.models import Base
-
# Configure SQLite to use URI mode, which allows for relative file paths
engine = create_engine(
app.config["SQLALCHEMY_DATABASE_URI"],
@@ -273,18 +269,12 @@ def create_database(app):
app.engine = engine
- # Create all tables
- Base.metadata.create_all(engine)
-
# Configure session factory
session_factory = sessionmaker(
bind=engine, autocommit=False, autoflush=False
)
app.db_session = scoped_session(session_factory)
- # Run migrations and setup predefined settings
- run_migrations(engine, app.db_session)
-
# Add teardown context
@app.teardown_appcontext
def remove_session(exception=None):
diff --git a/src/local_deep_research/web/database/migrate_to_ldr_db.py b/src/local_deep_research/web/database/migrate_to_ldr_db.py
deleted file mode 100644
index a9fb46057f..0000000000
--- a/src/local_deep_research/web/database/migrate_to_ldr_db.py
+++ /dev/null
@@ -1,297 +0,0 @@
-"""
-Migration script to merge deep_research.db and research_history.db into ldr.db
-"""
-
-# Standard library imports
-# import json # Remove unused imports
-import logging
-import os
-import sqlite3
-import sys
-import traceback
-
-# from pathlib import Path # Remove unused imports
-
-# Set up logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-# Add the parent directory to sys.path to allow relative imports
-sys.path.append(
- os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
-)
-
-# Import the database module after adding to sys path
-# pylint: disable=wrong-import-position
-from src.local_deep_research.web.models.database import ( # noqa: E402
- DB_PATH,
- LEGACY_DEEP_RESEARCH_DB,
- LEGACY_RESEARCH_HISTORY_DB,
-)
-
-
-def migrate_to_ldr_db():
- """
- Migrates data from deep_research.db and research_history.db to ldr.db
- """
- # Ensure data directory exists
- try:
- from src.local_deep_research.setup_data_dir import setup_data_dir
-
- setup_data_dir()
- except ImportError:
- # If we can't import directly, check the path manually
- logger.info("Creating data directory manually")
- data_dir = os.path.dirname(DB_PATH)
- os.makedirs(data_dir, exist_ok=True)
-
- logger.info(f"Using database path: {DB_PATH}")
-
- # Check if ldr.db already exists
- if os.path.exists(DB_PATH):
- logger.info(f"Target database {DB_PATH} already exists")
-
- # Ask for confirmation
- if (
- input(
- f"Target database {DB_PATH} already exists. Do you want to continue migration? (y/n): "
- ).lower()
- != "y"
- ):
- logger.info("Migration aborted by user")
- return False
-
- # Connect to the target database
- try:
- ldr_conn = sqlite3.connect(DB_PATH)
- ldr_cursor = ldr_conn.cursor()
- logger.info(f"Connected to target database: {DB_PATH}")
- except Exception as e:
- logger.error(f"Failed to connect to target database: {e}")
- return False
-
- # Enable foreign keys
- ldr_cursor.execute("PRAGMA foreign_keys = OFF")
-
- # Initialize the database schema
- try:
- from src.local_deep_research.web.models.database import init_db
-
- init_db()
- logger.info("Initialized database schema")
- except Exception as e:
- logger.error(f"Failed to initialize database schema: {e}")
- ldr_conn.close()
- return False
-
- # Migrate from research_history.db
- migrated_research = migrate_research_history_db(
- ldr_conn, LEGACY_RESEARCH_HISTORY_DB
- )
-
- # Migrate from deep_research.db
- migrated_deep_research = migrate_deep_research_db(
- ldr_conn, LEGACY_DEEP_RESEARCH_DB
- )
-
- # Re-enable foreign keys and commit
- ldr_cursor.execute("PRAGMA foreign_keys = ON")
- ldr_conn.commit()
- ldr_conn.close()
-
- logger.info(
- f"Migration completed - Research History: {migrated_research}, Deep Research: {migrated_deep_research}"
- )
- return True
-
-
-def migrate_research_history_db(ldr_conn, legacy_path):
- """
- Migrates data from research_history.db to ldr.db
-
- Args:
- ldr_conn: Connection to the target ldr.db
- legacy_path: Path to legacy research_history.db
-
- Returns:
- bool: True if migration was successful, False otherwise
- """
- if not os.path.exists(legacy_path):
- logger.warning(f"Legacy database not found: {legacy_path}")
- return False
-
- try:
- # Connect to legacy database
- legacy_conn = sqlite3.connect(legacy_path)
- legacy_cursor = legacy_conn.cursor()
- ldr_cursor = ldr_conn.cursor()
-
- logger.info(f"Connected to legacy database: {legacy_path}")
-
- # Get tables from legacy database
- legacy_cursor.execute(
- "SELECT name FROM sqlite_master WHERE type='table'"
- )
- tables = [row[0] for row in legacy_cursor.fetchall()]
-
- for table in tables:
- # Skip sqlite internal tables
- if table.startswith("sqlite_"):
- continue
-
- logger.info(f"Migrating table: {table}")
-
- # Check if table exists in target database
- ldr_cursor.execute(
- f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table}'"
- )
- if not ldr_cursor.fetchone():
- # Create the table in the target database
- legacy_cursor.execute(
- f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table}'"
- )
- create_sql = legacy_cursor.fetchone()[0]
- logger.info(f"Creating table {table} with SQL: {create_sql}")
- ldr_cursor.execute(create_sql)
- logger.info(f"Created table {table} in target database")
-
- # Get column names
- legacy_cursor.execute(f"PRAGMA table_info({table})")
- columns = [row[1] for row in legacy_cursor.fetchall()]
-
- # Get all data from legacy table
- legacy_cursor.execute(f"SELECT * FROM {table}")
- rows = legacy_cursor.fetchall()
-
- logger.info(f"Found {len(rows)} rows in {table}")
-
- if rows:
- # Create placeholders for the SQL query
- placeholders = ", ".join(["?" for _ in columns])
- columns_str = ", ".join(columns)
-
- # Insert data into target database
- for row in rows:
- try:
- ldr_cursor.execute(
- f"INSERT OR IGNORE INTO {table} ({columns_str}) VALUES ({placeholders})",
- row,
- )
- except sqlite3.Error as e:
- logger.error(f"Error inserting into {table}: {e}")
- logger.error(f"Row data: {row}")
- continue
-
- # Verify data was inserted
- ldr_cursor.execute(f"SELECT COUNT(*) FROM {table}")
- count = ldr_cursor.fetchone()[0]
- logger.info(
- f"Migrated {count} rows to {table} (expected {len(rows)})"
- )
- else:
- logger.info(f"No data to migrate from {table}")
-
- legacy_conn.close()
- return True
-
- except Exception as e:
- logger.error(f"Failed to migrate from {legacy_path}: {e}")
- logger.error(f"Exception details: {traceback.format_exc()}")
- return False
-
-
-def migrate_deep_research_db(ldr_conn, legacy_path):
- """
- Migrates data from deep_research.db to ldr.db
-
- Args:
- ldr_conn: Connection to the target ldr.db
- legacy_path: Path to legacy deep_research.db
-
- Returns:
- bool: True if migration was successful, False otherwise
- """
- if not os.path.exists(legacy_path):
- logger.warning(f"Legacy database not found: {legacy_path}")
- return False
-
- try:
- # Connect to legacy database
- legacy_conn = sqlite3.connect(legacy_path)
- legacy_cursor = legacy_conn.cursor()
- ldr_cursor = ldr_conn.cursor()
-
- logger.info(f"Connected to legacy database: {legacy_path}")
-
- # Get tables from legacy database
- legacy_cursor.execute(
- "SELECT name FROM sqlite_master WHERE type='table'"
- )
- tables = [row[0] for row in legacy_cursor.fetchall()]
-
- # Migrate each table
- for table in tables:
- # Skip sqlite internal tables
- if table.startswith("sqlite_"):
- continue
-
- # Skip the research_log table as it's redundant with research_logs
- if table == "research_log":
- logger.info(
- "Skipping redundant table 'research_log', using 'research_logs' instead"
- )
- continue
-
- logger.info(f"Migrating table: {table}")
-
- # Check if table exists in target database
- ldr_cursor.execute(
- f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table}'"
- )
- if not ldr_cursor.fetchone():
- # Create the table in the target database
- legacy_cursor.execute(
- f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table}'"
- )
- create_sql = legacy_cursor.fetchone()[0]
- ldr_cursor.execute(create_sql)
- logger.info(f"Created table {table} in target database")
-
- # Get column names
- legacy_cursor.execute(f"PRAGMA table_info({table})")
- columns = [row[1] for row in legacy_cursor.fetchall()]
-
- # Get all data from legacy table
- legacy_cursor.execute(f"SELECT * FROM {table}")
- rows = legacy_cursor.fetchall()
-
- if rows:
- # Create placeholders for the SQL query
- placeholders = ", ".join(["?" for _ in columns])
- columns_str = ", ".join(columns)
-
- # Insert data into target database
- for row in rows:
- try:
- ldr_cursor.execute(
- f"INSERT OR IGNORE INTO {table} ({columns_str}) VALUES ({placeholders})",
- row,
- )
- except sqlite3.Error as e:
- logger.error(f"Error inserting into {table}: {e}")
- continue
-
- logger.info(f"Migrated {len(rows)} rows from {table}")
- else:
- logger.info(f"No data to migrate from {table}")
-
- legacy_conn.close()
- return True
-
- except Exception as e:
- logger.error(f"Failed to migrate from {legacy_path}: {e}")
- return False
-
-
-if __name__ == "__main__":
- migrate_to_ldr_db()
diff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.py
index 200dfba654..6890732a29 100644
--- a/src/local_deep_research/web/database/migrations.py
+++ b/src/local_deep_research/web/database/migrations.py
@@ -1,9 +1,18 @@
+import sqlite3
+import uuid
+from pathlib import Path
+
from loguru import logger
+from sqlalchemy import inspect, text, create_engine
from ..services.settings_manager import SettingsManager
from .models import (
Base,
+ ResearchStrategy,
+ RateLimitAttempt,
+ RateLimitEstimate,
)
+from ...utilities.db_utils import DB_PATH, get_db_session
def import_default_settings_file(db_session):
@@ -27,21 +36,708 @@ def import_default_settings_file(db_session):
# Update the saved version.
settings_mgr.update_db_version()
+ except Exception:
+ logger.exception("Error importing settings from files")
+
+
+def remove_research_log_table(engine):
+ """
+ Remove the redundant research_log table if it exists
+
+ Args:
+ engine: SQLAlchemy engine
+
+ Returns:
+ bool: True if operation was successful, False otherwise
+ """
+ try:
+ inspector = inspect(engine)
+
+ # Check if table exists
+ if inspector.has_table("research_log"):
+ # For SQLite, we need to use raw SQL for DROP TABLE
+ with engine.connect() as conn:
+ conn.execute("DROP TABLE research_log")
+ conn.commit()
+ logger.info("Successfully removed redundant 'research_log' table")
+ return True
+ else:
+ logger.info("Table 'research_log' does not exist, no action needed")
+ return True
+ except Exception:
+ logger.exception("Error removing research_log table")
+ return False
+
+
+def create_research_strategy_table(engine):
+ """
+ Create the research_strategies table if it doesn't exist
+
+ Args:
+ engine: SQLAlchemy engine
+
+ Returns:
+ bool: True if operation was successful, False otherwise
+ """
+ try:
+ inspector = inspect(engine)
+
+ # Check if table exists
+ if not inspector.has_table("research_strategies"):
+ # Create the table using ORM
+ Base.metadata.create_all(
+ engine, tables=[ResearchStrategy.__table__]
+ )
+ logger.info("Successfully created 'research_strategies' table")
+ return True
+ else:
+ logger.info(
+ "Table 'research_strategies' already exists, no action needed"
+ )
+ return True
+ except Exception:
+ logger.exception("Error creating research_strategies table")
+ return False
+
+
+def create_rate_limiting_tables(engine):
+ """
+ Create rate limiting tables if they don't exist
+
+ Args:
+ engine: SQLAlchemy engine
+
+ Returns:
+ bool: True if operation was successful, False otherwise
+ """
+ try:
+ inspector = inspect(engine)
+
+ tables_to_create = []
+
+ # Check if rate_limit_attempts table exists
+ if not inspector.has_table("rate_limit_attempts"):
+ tables_to_create.append(RateLimitAttempt.__table__)
+ logger.info("Need to create 'rate_limit_attempts' table")
+
+ # Check if rate_limit_estimates table exists
+ if not inspector.has_table("rate_limit_estimates"):
+ tables_to_create.append(RateLimitEstimate.__table__)
+ logger.info("Need to create 'rate_limit_estimates' table")
+
+ if tables_to_create:
+ # Create the tables using ORM
+ Base.metadata.create_all(engine, tables=tables_to_create)
+ logger.info(
+ f"Successfully created {len(tables_to_create)} rate limiting tables"
+ )
+ else:
+ logger.info("Rate limiting tables already exist, no action needed")
+
+ return True
+ except Exception:
+ logger.exception("Error creating rate limiting tables")
+ return False
+
+
+def add_research_id_to_benchmark_results(engine):
+ """
+ Add research_id column to benchmark_results table if it doesn't exist.
+ """
+ try:
+ import sqlite3
+
+ # Get database path from engine
+ db_path = engine.url.database
+
+ logger.info("Checking if benchmark_results needs research_id column...")
+
+ conn = sqlite3.connect(db_path)
+
+ try:
+ cursor = conn.cursor()
+
+ # Check if table exists
+ cursor.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='benchmark_results'"
+ )
+ if not cursor.fetchone():
+ logger.info("benchmark_results table does not exist, skipping")
+ return True
+
+ # Check if research_id column already exists
+ cursor.execute("PRAGMA table_info(benchmark_results)")
+ columns = cursor.fetchall()
+ has_research_id = any(col[1] == "research_id" for col in columns)
+
+ if has_research_id:
+ logger.info("benchmark_results already has research_id column")
+ return True
+
+ # Add research_id column
+ logger.info("Adding research_id column to benchmark_results table")
+ cursor.execute(
+ "ALTER TABLE benchmark_results ADD COLUMN research_id TEXT"
+ )
+
+ conn.commit()
+ logger.info(
+ "Successfully added research_id column to benchmark_results"
+ )
+ return True
+
+ finally:
+ conn.close()
+
+ except Exception:
+ logger.exception("Error adding research_id column to benchmark_results")
+ return False
+
+
+def add_uuid_id_column_to_research_history(engine):
+ """
+ Adds a new `uuid_id` string column to the `research_history` table if it
+ does not exist already.
+ """
+ try:
+ import sqlite3
+
+ # Get database path from engine
+ db_path = engine.url.database
+
+ logger.info("Checking if research_history needs uuid_id column...")
+
+ conn = sqlite3.connect(db_path)
+
+ try:
+ cursor = conn.cursor()
+
+ # Check if table exists
+ cursor.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='research_history'"
+ )
+ if not cursor.fetchone():
+ logger.info("research_history table does not exist, skipping")
+ return True
+
+ # Check if uuid_id column already exists
+ cursor.execute("PRAGMA table_info(research_history)")
+ columns = cursor.fetchall()
+ has_uuid_id = any(col[1] == "uuid_id" for col in columns)
+
+ if has_uuid_id:
+ logger.info("research_history already has uuid_id column")
+ return True
+
+ # Add uuid_id column
+ logger.info("Adding uuid_id column to research_history table")
+ cursor.execute(
+ "ALTER TABLE research_history ADD COLUMN uuid_id CHAR(36)"
+ )
+
+ conn.commit()
+ logger.info("Successfully added uuid_id column to research_history")
+ return True
+
+ finally:
+ conn.close()
+
+ except Exception:
+ logger.exception("Error adding uuid_id column to research_history")
+ return False
+
+
+def convert_research_id_to_string_if_needed(engine):
+ """
+ Convert research_id columns from Integer to String in all tables.
+ Preserves existing data by converting integer IDs to string format.
+ Only runs if integer research_id columns are detected.
+ """
+ try:
+ import sqlite3
+
+ # Get database path from engine
+ db_path = engine.url.database
+
+ logger.info(
+ "Checking if research_id columns need conversion to string..."
+ )
+
+ conn = sqlite3.connect(db_path)
+ conn.execute("PRAGMA foreign_keys = OFF")
+
+ try:
+ cursor = conn.cursor()
+
+ # List of tables that might have research_id columns
+ tables_to_check = [
+ "token_usage",
+ "model_usage",
+ "search_calls",
+ "benchmark_results",
+ ]
+
+ tables_needing_conversion = []
+
+ # Check which tables need conversion
+ for table_name in tables_to_check:
+ # Check if table exists
+ cursor.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
+ (table_name,),
+ )
+ if not cursor.fetchone():
+ continue
+
+ # Check if research_id column exists and is integer type
+ cursor.execute(f"PRAGMA table_info({table_name})")
+ columns = cursor.fetchall()
+
+ for col in columns:
+ col_name, col_type = col[1], col[2]
+ if col_name == "research_id" and (
+ "INTEGER" in col_type.upper()
+ or "INT" in col_type.upper()
+ ):
+ tables_needing_conversion.append(table_name)
+ break
+
+ if not tables_needing_conversion:
+ logger.info(
+ "All research_id columns are already string type, no conversion needed"
+ )
+ return True
+
+ logger.info(
+ f"Converting research_id to string in tables: {tables_needing_conversion}"
+ )
+
+ # Convert each table
+ for table_name in tables_needing_conversion:
+ logger.info(f"Converting {table_name} table...")
+
+ # Get the current table schema
+ cursor.execute(
+ f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table_name}'"
+ )
+ create_sql = cursor.fetchone()[0]
+
+ # Create new table name
+ new_table_name = f"{table_name}_new"
+
+ # Modify the CREATE TABLE statement to change research_id to TEXT
+ new_create_sql = create_sql.replace(
+ f"CREATE TABLE {table_name}",
+ f"CREATE TABLE {new_table_name}",
+ )
+ new_create_sql = new_create_sql.replace(
+ "research_id INTEGER", "research_id TEXT"
+ )
+ new_create_sql = new_create_sql.replace(
+ "research_id INT", "research_id TEXT"
+ )
+
+ # Create the new table
+ cursor.execute(new_create_sql)
+
+ # Copy data from old table to new table, converting research_id to string
+ cursor.execute(f"SELECT * FROM {table_name}")
+ old_rows = cursor.fetchall()
+
+ if old_rows:
+ # Get column names
+ cursor.execute(f"PRAGMA table_info({table_name})")
+ columns = cursor.fetchall()
+ column_names = [col[1] for col in columns]
+ research_id_index = (
+ column_names.index("research_id")
+ if "research_id" in column_names
+ else -1
+ )
+
+ # Prepare insert statement
+ placeholders = ",".join(["?" for _ in column_names])
+ insert_sql = f"INSERT INTO {new_table_name} ({','.join(column_names)}) VALUES ({placeholders})"
+
+ # Convert rows and insert
+ converted_rows = []
+ for row in old_rows:
+ row_list = list(row)
+ # Convert research_id to string if it's not None
+ if (
+ research_id_index >= 0
+ and row_list[research_id_index] is not None
+ ):
+ row_list[research_id_index] = str(
+ row_list[research_id_index]
+ )
+ converted_rows.append(tuple(row_list))
+
+ cursor.executemany(insert_sql, converted_rows)
+ logger.info(
+ f"Converted {len(converted_rows)} rows in {table_name}"
+ )
+
+ # Drop old table and rename new table
+ cursor.execute(f"DROP TABLE {table_name}")
+ cursor.execute(
+ f"ALTER TABLE {new_table_name} RENAME TO {table_name}"
+ )
+
+ logger.info(
+ f"Successfully converted {table_name} research_id to string"
+ )
+
+ # Commit all changes
+ conn.commit()
+ logger.info(
+ "All research_id columns converted to string successfully!"
+ )
+ return True
+
+ finally:
+ conn.execute("PRAGMA foreign_keys = ON")
+ conn.close()
+
+ except Exception:
+ logger.exception("Error converting research_id columns to string")
+ return False
+
+
+def create_provider_models_table(engine):
+ """Create provider_models table for caching available models"""
+ with engine.connect() as conn:
+ result = conn.execute(
+ text(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='provider_models'"
+ )
+ )
+ if result.fetchone():
+ logger.info(
+ "Table 'provider_models' already exists, no action needed"
+ )
+ return
+
+ logger.info("Creating 'provider_models' table...")
+
+ # Create the table
+ conn.execute(
+ text(
+ """
+ CREATE TABLE provider_models (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ provider VARCHAR(50) NOT NULL,
+ model_key VARCHAR(255) NOT NULL,
+ model_label VARCHAR(255) NOT NULL,
+ model_metadata JSON,
+ last_updated DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ UNIQUE(provider, model_key)
+ )
+ """
+ )
+ )
+
+ # Create index on provider
+ conn.execute(
+ text(
+ "CREATE INDEX ix_provider_models_provider ON provider_models (provider)"
+ )
+ )
+
+ conn.commit()
+ logger.info("Table 'provider_models' created successfully")
+
+
+def migrate_to_uuid():
+ """
+ Migrate all research_id fields from integers to UUIDs.
+
+ Strategy:
+ 1. Add new UUID columns alongside existing integer columns
+ 2. Generate UUIDs for existing data (or keep as string versions of integers)
+ 3. Update foreign key relationships
+ 4. Drop old integer columns and rename UUID columns
+ """
+ db_path = Path(DB_PATH)
+ if not db_path.exists():
+ logger.info("Database doesn't exist yet, migration not needed")
+ return
+
+ logger.info(f"Starting UUID migration on {db_path}")
+
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ "PRAGMA foreign_keys = OFF"
+ ) # Disable FK constraints during migration
+
+ try:
+ cursor = conn.cursor()
+
+ # 1. Migrate research_history table (main research IDs)
+ logger.info("Migrating research_history table...")
+
+ # Check if the table exists and has the old structure
+ cursor.execute("PRAGMA table_info(research_history)")
+ columns = cursor.fetchall()
+ has_uuid_id = any(col[1] == "uuid_id" for col in columns)
+
+ if not has_uuid_id:
+ # Add UUID column
+ cursor.execute(
+ "ALTER TABLE research_history ADD COLUMN uuid_id TEXT"
+ )
+
+ # Generate UUIDs for existing records (convert integer ID to UUID format)
+ cursor.execute("SELECT id FROM research_history")
+ existing_ids = cursor.fetchall()
+
+ for (old_id,) in existing_ids:
+ # Generate a deterministic UUID based on the old ID
+ new_uuid = str(
+ uuid.uuid5(uuid.NAMESPACE_OID, f"research_{old_id}")
+ )
+ cursor.execute(
+ "UPDATE research_history SET uuid_id = ? WHERE id = ?",
+ (new_uuid, old_id),
+ )
+
+ logger.info(
+ f"Generated UUIDs for {len(existing_ids)} research records"
+ )
+
+ # 2. Migrate metrics tables
+ logger.info("Migrating metrics tables...")
+
+ # Token usage table
+ cursor.execute("PRAGMA table_info(token_usage)")
+ columns = cursor.fetchall()
+ has_uuid_research_id = any(
+ col[1] == "uuid_research_id" for col in columns
+ )
+
+ if not has_uuid_research_id:
+ cursor.execute(
+ "ALTER TABLE token_usage ADD COLUMN uuid_research_id TEXT"
+ )
+
+ # Convert existing research_ids to UUIDs (deterministic conversion)
+ cursor.execute(
+ "SELECT DISTINCT research_id FROM token_usage WHERE research_id IS NOT NULL"
+ )
+ research_ids = cursor.fetchall()
+
+ for (research_id,) in research_ids:
+ if research_id:
+ new_uuid = str(
+ uuid.uuid5(
+ uuid.NAMESPACE_OID, f"research_{research_id}"
+ )
+ )
+ cursor.execute(
+ "UPDATE token_usage SET uuid_research_id = ? WHERE research_id = ?",
+ (new_uuid, research_id),
+ )
+
+ logger.info(
+ f"Migrated {len(research_ids)} research IDs in token_usage"
+ )
+
+ # Model usage table
+ cursor.execute("PRAGMA table_info(model_usage)")
+ columns = cursor.fetchall()
+ has_uuid_research_id = any(
+ col[1] == "uuid_research_id" for col in columns
+ )
+
+ if not has_uuid_research_id:
+ cursor.execute(
+ "ALTER TABLE model_usage ADD COLUMN uuid_research_id TEXT"
+ )
+
+ cursor.execute(
+ "SELECT DISTINCT research_id FROM model_usage WHERE research_id IS NOT NULL"
+ )
+ research_ids = cursor.fetchall()
+
+ for (research_id,) in research_ids:
+ if research_id:
+ new_uuid = str(
+ uuid.uuid5(
+ uuid.NAMESPACE_OID, f"research_{research_id}"
+ )
+ )
+ cursor.execute(
+ "UPDATE model_usage SET uuid_research_id = ? WHERE research_id = ?",
+ (new_uuid, research_id),
+ )
+
+ logger.info(
+ f"Migrated {len(research_ids)} research IDs in model_usage"
+ )
+
+ # Search calls table
+ cursor.execute("PRAGMA table_info(search_calls)")
+ columns = cursor.fetchall()
+ has_uuid_research_id = any(
+ col[1] == "uuid_research_id" for col in columns
+ )
+
+ if not has_uuid_research_id:
+ cursor.execute(
+ "ALTER TABLE search_calls ADD COLUMN uuid_research_id TEXT"
+ )
+
+ cursor.execute(
+ "SELECT DISTINCT research_id FROM search_calls WHERE research_id IS NOT NULL"
+ )
+ research_ids = cursor.fetchall()
+
+ for (research_id,) in research_ids:
+ if research_id:
+ new_uuid = str(
+ uuid.uuid5(
+ uuid.NAMESPACE_OID, f"research_{research_id}"
+ )
+ )
+ cursor.execute(
+ "UPDATE search_calls SET uuid_research_id = ? WHERE research_id = ?",
+ (new_uuid, research_id),
+ )
+
+ logger.info(
+ f"Migrated {len(research_ids)} research IDs in search_calls"
+ )
+
+ # 3. Migrate benchmark tables
+ logger.info("Migrating benchmark tables...")
+
+ # Check if benchmark_results table exists
+ cursor.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='benchmark_results'"
+ )
+ if cursor.fetchone():
+ cursor.execute("PRAGMA table_info(benchmark_results)")
+ columns = cursor.fetchall()
+ has_uuid_research_id = any(
+ col[1] == "uuid_research_id" for col in columns
+ )
+
+ if not has_uuid_research_id:
+ cursor.execute(
+ "ALTER TABLE benchmark_results ADD COLUMN uuid_research_id TEXT"
+ )
+
+ cursor.execute(
+ "SELECT DISTINCT research_id FROM benchmark_results WHERE research_id IS NOT NULL"
+ )
+ research_ids = cursor.fetchall()
+
+ for (research_id,) in research_ids:
+ if research_id:
+ new_uuid = str(
+ uuid.uuid5(
+ uuid.NAMESPACE_OID, f"research_{research_id}"
+ )
+ )
+ cursor.execute(
+ "UPDATE benchmark_results SET uuid_research_id = ? WHERE research_id = ?",
+ (new_uuid, research_id),
+ )
+
+ logger.info(
+ f"Migrated {len(research_ids)} research IDs in benchmark_results"
+ )
+
+ # Commit all changes
+ conn.commit()
+ logger.info("UUID migration completed successfully!")
+
+ # Note: We're keeping both old and new columns for now
+ # The application will use the new UUID columns
+ # Old columns can be dropped in a future migration once everything is stable
+
except Exception as e:
- logger.error("Error importing settings from files: %s", e)
+ logger.error(f"Error during UUID migration: {e}")
+ conn.rollback()
+ raise
+ finally:
+ conn.execute("PRAGMA foreign_keys = ON") # Re-enable FK constraints
+ conn.close()
-def run_migrations(engine, db_session=None):
+def cleanup_old_columns():
"""
- Run any necessary database migrations
+ Cleanup migration - drops old integer columns after UUID migration is stable.
+ Run this only after confirming the UUID migration is working correctly.
+ """
+ logger.warning(
+ "This will permanently remove old integer research_id columns!"
+ )
+ logger.warning("Make sure to backup your database before running this!")
+
+ conn = sqlite3.connect(DB_PATH)
+ conn.execute("PRAGMA foreign_keys = OFF")
+
+ try:
+ # For SQLite, we need to recreate tables to drop columns
+ # This is complex, so we'll leave old columns for now
+ # They can be cleaned up manually if needed
+
+ logger.info("Cleanup deferred - old columns remain for safety")
+
+ finally:
+ conn.execute("PRAGMA foreign_keys = ON")
+ conn.close()
+
+
+def ensure_database_initialized(engine=None, db_session=None):
+ """
+ Initialize the database and run any necessary database migrations
Args:
engine: SQLAlchemy engine
db_session: Optional SQLAlchemy session
"""
+ logger.info("Initializing database at {}.", DB_PATH)
+
+ if engine is None:
+ # Create SQLAlchemy engine
+ engine = create_engine(f"sqlite:///{DB_PATH}")
+ if db_session is None:
+ db_session = get_db_session()
+
# Create all tables if they don't exist
Base.metadata.create_all(engine)
# Import existing settings from files
- if db_session:
- import_default_settings_file(db_session)
+ import_default_settings_file(db_session)
+
+ try:
+ # 1. Remove the redundant research_log table
+ remove_research_log_table(engine)
+
+ # 2. Create research_strategies table
+ create_research_strategy_table(engine)
+
+ # 4. Create rate limiting tables
+ create_rate_limiting_tables(engine)
+
+ # 5. Add research_id column to benchmark_results if missing
+ add_research_id_to_benchmark_results(engine)
+
+ # 6. Convert research_id columns from integer to string
+ convert_research_id_to_string_if_needed(engine)
+
+ # 7. Add uuid_id column to research_history if missing
+ add_uuid_id_column_to_research_history(engine)
+
+ # 8. Create provider_models table for caching
+ create_provider_models_table(engine)
+
+ logger.info("Schema upgrades completed successfully")
+ return True
+ except Exception:
+ logger.exception("Error during schema upgrades")
+ return False
+ finally:
+ db_session.close()
diff --git a/src/local_deep_research/web/database/schema_upgrade.py b/src/local_deep_research/web/database/schema_upgrade.py
deleted file mode 100644
index 19900626c2..0000000000
--- a/src/local_deep_research/web/database/schema_upgrade.py
+++ /dev/null
@@ -1,487 +0,0 @@
-"""
-Schema upgrade script for Local Deep Research database.
-Handles schema upgrades for existing ldr.db databases.
-"""
-
-import os
-import sys
-
-from loguru import logger
-from sqlalchemy import create_engine, inspect, text
-
-# Add the parent directory to sys.path to allow relative imports
-sys.path.append(
- os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
-)
-
-try:
- from src.local_deep_research.web.models.database import DB_PATH
-except ImportError:
- # Fallback path if import fails
- current_dir = os.path.dirname(os.path.abspath(__file__))
- project_root = os.path.abspath(
- os.path.join(current_dir, "..", "..", "..", "..")
- )
- DB_PATH = os.path.join(project_root, "src", "data", "ldr.db")
-
-from .models import Base, ResearchStrategy, RateLimitAttempt, RateLimitEstimate
-
-
-def remove_research_log_table(engine):
- """
- Remove the redundant research_log table if it exists
-
- Args:
- engine: SQLAlchemy engine
-
- Returns:
- bool: True if operation was successful, False otherwise
- """
- try:
- inspector = inspect(engine)
-
- # Check if table exists
- if inspector.has_table("research_log"):
- # For SQLite, we need to use raw SQL for DROP TABLE
- with engine.connect() as conn:
- conn.execute("DROP TABLE research_log")
- conn.commit()
- logger.info("Successfully removed redundant 'research_log' table")
- return True
- else:
- logger.info("Table 'research_log' does not exist, no action needed")
- return True
- except Exception:
- logger.exception("Error removing research_log table")
- return False
-
-
-def create_research_strategy_table(engine):
- """
- Create the research_strategies table if it doesn't exist
-
- Args:
- engine: SQLAlchemy engine
-
- Returns:
- bool: True if operation was successful, False otherwise
- """
- try:
- inspector = inspect(engine)
-
- # Check if table exists
- if not inspector.has_table("research_strategies"):
- # Create the table using ORM
- Base.metadata.create_all(
- engine, tables=[ResearchStrategy.__table__]
- )
- logger.info("Successfully created 'research_strategies' table")
- return True
- else:
- logger.info(
- "Table 'research_strategies' already exists, no action needed"
- )
- return True
- except Exception:
- logger.exception("Error creating research_strategies table")
- return False
-
-
-def create_rate_limiting_tables(engine):
- """
- Create rate limiting tables if they don't exist
-
- Args:
- engine: SQLAlchemy engine
-
- Returns:
- bool: True if operation was successful, False otherwise
- """
- try:
- inspector = inspect(engine)
-
- tables_to_create = []
-
- # Check if rate_limit_attempts table exists
- if not inspector.has_table("rate_limit_attempts"):
- tables_to_create.append(RateLimitAttempt.__table__)
- logger.info("Need to create 'rate_limit_attempts' table")
-
- # Check if rate_limit_estimates table exists
- if not inspector.has_table("rate_limit_estimates"):
- tables_to_create.append(RateLimitEstimate.__table__)
- logger.info("Need to create 'rate_limit_estimates' table")
-
- if tables_to_create:
- # Create the tables using ORM
- Base.metadata.create_all(engine, tables=tables_to_create)
- logger.info(
- f"Successfully created {len(tables_to_create)} rate limiting tables"
- )
- else:
- logger.info("Rate limiting tables already exist, no action needed")
-
- return True
- except Exception:
- logger.exception("Error creating rate limiting tables")
- return False
-
-
-def add_research_id_to_benchmark_results(engine):
- """
- Add research_id column to benchmark_results table if it doesn't exist.
- """
- try:
- import sqlite3
-
- # Get database path from engine
- db_path = engine.url.database
-
- logger.info("Checking if benchmark_results needs research_id column...")
-
- conn = sqlite3.connect(db_path)
-
- try:
- cursor = conn.cursor()
-
- # Check if table exists
- cursor.execute(
- "SELECT name FROM sqlite_master WHERE type='table' AND name='benchmark_results'"
- )
- if not cursor.fetchone():
- logger.info("benchmark_results table does not exist, skipping")
- return True
-
- # Check if research_id column already exists
- cursor.execute("PRAGMA table_info(benchmark_results)")
- columns = cursor.fetchall()
- has_research_id = any(col[1] == "research_id" for col in columns)
-
- if has_research_id:
- logger.info("benchmark_results already has research_id column")
- return True
-
- # Add research_id column
- logger.info("Adding research_id column to benchmark_results table")
- cursor.execute(
- "ALTER TABLE benchmark_results ADD COLUMN research_id TEXT"
- )
-
- conn.commit()
- logger.info(
- "Successfully added research_id column to benchmark_results"
- )
- return True
-
- finally:
- conn.close()
-
- except Exception:
- logger.exception("Error adding research_id column to benchmark_results")
- return False
-
-
-def add_uuid_id_column_to_research_history(engine):
- """
- Adds a new `uuid_id` string column to the `research_history` table if it
- does not exist already.
- """
- try:
- import sqlite3
-
- # Get database path from engine
- db_path = engine.url.database
-
- logger.info("Checking if research_history needs uuid_id column...")
-
- conn = sqlite3.connect(db_path)
-
- try:
- cursor = conn.cursor()
-
- # Check if table exists
- cursor.execute(
- "SELECT name FROM sqlite_master WHERE type='table' AND name='research_history'"
- )
- if not cursor.fetchone():
- logger.info("research_history table does not exist, skipping")
- return True
-
- # Check if uuid_id column already exists
- cursor.execute("PRAGMA table_info(research_history)")
- columns = cursor.fetchall()
- has_uuid_id = any(col[1] == "uuid_id" for col in columns)
-
- if has_uuid_id:
- logger.info("research_history already has uuid_id column")
- return True
-
- # Add uuid_id column
- logger.info("Adding uuid_id column to research_history table")
- cursor.execute(
- "ALTER TABLE research_history ADD COLUMN uuid_id CHAR(36)"
- )
-
- conn.commit()
- logger.info("Successfully added uuid_id column to research_history")
- return True
-
- finally:
- conn.close()
-
- except Exception:
- logger.exception("Error adding uuid_id column to research_history")
- return False
-
-
-def convert_research_id_to_string_if_needed(engine):
- """
- Convert research_id columns from Integer to String in all tables.
- Preserves existing data by converting integer IDs to string format.
- Only runs if integer research_id columns are detected.
- """
- try:
- import sqlite3
-
- # Get database path from engine
- db_path = engine.url.database
-
- logger.info(
- "Checking if research_id columns need conversion to string..."
- )
-
- conn = sqlite3.connect(db_path)
- conn.execute("PRAGMA foreign_keys = OFF")
-
- try:
- cursor = conn.cursor()
-
- # List of tables that might have research_id columns
- tables_to_check = [
- "token_usage",
- "model_usage",
- "search_calls",
- "benchmark_results",
- ]
-
- tables_needing_conversion = []
-
- # Check which tables need conversion
- for table_name in tables_to_check:
- # Check if table exists
- cursor.execute(
- "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
- (table_name,),
- )
- if not cursor.fetchone():
- continue
-
- # Check if research_id column exists and is integer type
- cursor.execute(f"PRAGMA table_info({table_name})")
- columns = cursor.fetchall()
-
- for col in columns:
- col_name, col_type = col[1], col[2]
- if col_name == "research_id" and (
- "INTEGER" in col_type.upper()
- or "INT" in col_type.upper()
- ):
- tables_needing_conversion.append(table_name)
- break
-
- if not tables_needing_conversion:
- logger.info(
- "All research_id columns are already string type, no conversion needed"
- )
- return True
-
- logger.info(
- f"Converting research_id to string in tables: {tables_needing_conversion}"
- )
-
- # Convert each table
- for table_name in tables_needing_conversion:
- logger.info(f"Converting {table_name} table...")
-
- # Get the current table schema
- cursor.execute(
- f"SELECT sql FROM sqlite_master WHERE type='table' AND name='{table_name}'"
- )
- create_sql = cursor.fetchone()[0]
-
- # Create new table name
- new_table_name = f"{table_name}_new"
-
- # Modify the CREATE TABLE statement to change research_id to TEXT
- new_create_sql = create_sql.replace(
- f"CREATE TABLE {table_name}",
- f"CREATE TABLE {new_table_name}",
- )
- new_create_sql = new_create_sql.replace(
- "research_id INTEGER", "research_id TEXT"
- )
- new_create_sql = new_create_sql.replace(
- "research_id INT", "research_id TEXT"
- )
-
- # Create the new table
- cursor.execute(new_create_sql)
-
- # Copy data from old table to new table, converting research_id to string
- cursor.execute(f"SELECT * FROM {table_name}")
- old_rows = cursor.fetchall()
-
- if old_rows:
- # Get column names
- cursor.execute(f"PRAGMA table_info({table_name})")
- columns = cursor.fetchall()
- column_names = [col[1] for col in columns]
- research_id_index = (
- column_names.index("research_id")
- if "research_id" in column_names
- else -1
- )
-
- # Prepare insert statement
- placeholders = ",".join(["?" for _ in column_names])
- insert_sql = f"INSERT INTO {new_table_name} ({','.join(column_names)}) VALUES ({placeholders})"
-
- # Convert rows and insert
- converted_rows = []
- for row in old_rows:
- row_list = list(row)
- # Convert research_id to string if it's not None
- if (
- research_id_index >= 0
- and row_list[research_id_index] is not None
- ):
- row_list[research_id_index] = str(
- row_list[research_id_index]
- )
- converted_rows.append(tuple(row_list))
-
- cursor.executemany(insert_sql, converted_rows)
- logger.info(
- f"Converted {len(converted_rows)} rows in {table_name}"
- )
-
- # Drop old table and rename new table
- cursor.execute(f"DROP TABLE {table_name}")
- cursor.execute(
- f"ALTER TABLE {new_table_name} RENAME TO {table_name}"
- )
-
- logger.info(
- f"Successfully converted {table_name} research_id to string"
- )
-
- # Commit all changes
- conn.commit()
- logger.info(
- "All research_id columns converted to string successfully!"
- )
- return True
-
- finally:
- conn.execute("PRAGMA foreign_keys = ON")
- conn.close()
-
- except Exception:
- logger.exception("Error converting research_id columns to string")
- return False
-
-
-def create_provider_models_table(engine):
- """Create provider_models table for caching available models"""
- with engine.connect() as conn:
- result = conn.execute(
- text(
- "SELECT name FROM sqlite_master WHERE type='table' AND name='provider_models'"
- )
- )
- if result.fetchone():
- logger.info(
- "Table 'provider_models' already exists, no action needed"
- )
- return
-
- logger.info("Creating 'provider_models' table...")
-
- # Create the table
- conn.execute(
- text(
- """
- CREATE TABLE provider_models (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- provider VARCHAR(50) NOT NULL,
- model_key VARCHAR(255) NOT NULL,
- model_label VARCHAR(255) NOT NULL,
- model_metadata JSON,
- last_updated DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
- UNIQUE(provider, model_key)
- )
- """
- )
- )
-
- # Create index on provider
- conn.execute(
- text(
- "CREATE INDEX ix_provider_models_provider ON provider_models (provider)"
- )
- )
-
- conn.commit()
- logger.info("Table 'provider_models' created successfully")
-
-
-def run_schema_upgrades():
- """
- Run all schema upgrade operations on the database
-
- Returns:
- bool: True if all upgrades successful, False otherwise
- """
- # Check if database exists
- if not os.path.exists(DB_PATH):
- logger.warning(
- f"Database not found at {DB_PATH}, skipping schema upgrades"
- )
- return False
-
- logger.info(f"Running schema upgrades on {DB_PATH}")
-
- try:
- # Create SQLAlchemy engine
- engine = create_engine(f"sqlite:///{DB_PATH}")
-
- # 1. Remove the redundant research_log table
- remove_research_log_table(engine)
-
- # 2. Create research_strategies table
- create_research_strategy_table(engine)
-
- # 4. Create rate limiting tables
- create_rate_limiting_tables(engine)
-
- # 5. Add research_id column to benchmark_results if missing
- add_research_id_to_benchmark_results(engine)
-
- # 6. Convert research_id columns from integer to string
- convert_research_id_to_string_if_needed(engine)
-
- # 7. Add uuid_id column to research_history if missing
- add_uuid_id_column_to_research_history(engine)
-
- # 8. Create provider_models table for caching
- create_provider_models_table(engine)
-
- logger.info("Schema upgrades completed successfully")
- return True
- except Exception:
- logger.exception("Error during schema upgrades")
- return False
-
-
-if __name__ == "__main__":
- run_schema_upgrades()
diff --git a/src/local_deep_research/web/database/uuid_migration.py b/src/local_deep_research/web/database/uuid_migration.py
index 2645e1022e..9471bbb1a8 100644
--- a/src/local_deep_research/web/database/uuid_migration.py
+++ b/src/local_deep_research/web/database/uuid_migration.py
@@ -5,10 +5,9 @@ Migrates all research_id fields from Integer to String (UUID) format.
This creates a more consistent and scalable ID system across the application.
"""
-import sqlite3
-import uuid
from pathlib import Path
-from loguru import logger
+
+from local_deep_research.web.database.migrations import migrate_to_uuid
def get_database_path():
@@ -17,249 +16,5 @@ def get_database_path():
return data_dir / "ldr.db"
-def migrate_to_uuid():
- """
- Migrate all research_id fields from integers to UUIDs.
-
- Strategy:
- 1. Add new UUID columns alongside existing integer columns
- 2. Generate UUIDs for existing data (or keep as string versions of integers)
- 3. Update foreign key relationships
- 4. Drop old integer columns and rename UUID columns
- """
- db_path = get_database_path()
-
- if not db_path.exists():
- logger.info("Database doesn't exist yet, migration not needed")
- return
-
- logger.info(f"Starting UUID migration on {db_path}")
-
- conn = sqlite3.connect(db_path)
- conn.execute(
- "PRAGMA foreign_keys = OFF"
- ) # Disable FK constraints during migration
-
- try:
- cursor = conn.cursor()
-
- # 1. Migrate research_history table (main research IDs)
- logger.info("Migrating research_history table...")
-
- # Check if the table exists and has the old structure
- cursor.execute("PRAGMA table_info(research_history)")
- columns = cursor.fetchall()
- has_uuid_id = any(col[1] == "uuid_id" for col in columns)
-
- if not has_uuid_id:
- # Add UUID column
- cursor.execute(
- "ALTER TABLE research_history ADD COLUMN uuid_id TEXT"
- )
-
- # Generate UUIDs for existing records (convert integer ID to UUID format)
- cursor.execute("SELECT id FROM research_history")
- existing_ids = cursor.fetchall()
-
- for (old_id,) in existing_ids:
- # Generate a deterministic UUID based on the old ID
- new_uuid = str(
- uuid.uuid5(uuid.NAMESPACE_OID, f"research_{old_id}")
- )
- cursor.execute(
- "UPDATE research_history SET uuid_id = ? WHERE id = ?",
- (new_uuid, old_id),
- )
-
- logger.info(
- f"Generated UUIDs for {len(existing_ids)} research records"
- )
-
- # 2. Migrate metrics tables
- logger.info("Migrating metrics tables...")
-
- # Token usage table
- cursor.execute("PRAGMA table_info(token_usage)")
- columns = cursor.fetchall()
- has_uuid_research_id = any(
- col[1] == "uuid_research_id" for col in columns
- )
-
- if not has_uuid_research_id:
- cursor.execute(
- "ALTER TABLE token_usage ADD COLUMN uuid_research_id TEXT"
- )
-
- # Convert existing research_ids to UUIDs (deterministic conversion)
- cursor.execute(
- "SELECT DISTINCT research_id FROM token_usage WHERE research_id IS NOT NULL"
- )
- research_ids = cursor.fetchall()
-
- for (research_id,) in research_ids:
- if research_id:
- new_uuid = str(
- uuid.uuid5(
- uuid.NAMESPACE_OID, f"research_{research_id}"
- )
- )
- cursor.execute(
- "UPDATE token_usage SET uuid_research_id = ? WHERE research_id = ?",
- (new_uuid, research_id),
- )
-
- logger.info(
- f"Migrated {len(research_ids)} research IDs in token_usage"
- )
-
- # Model usage table
- cursor.execute("PRAGMA table_info(model_usage)")
- columns = cursor.fetchall()
- has_uuid_research_id = any(
- col[1] == "uuid_research_id" for col in columns
- )
-
- if not has_uuid_research_id:
- cursor.execute(
- "ALTER TABLE model_usage ADD COLUMN uuid_research_id TEXT"
- )
-
- cursor.execute(
- "SELECT DISTINCT research_id FROM model_usage WHERE research_id IS NOT NULL"
- )
- research_ids = cursor.fetchall()
-
- for (research_id,) in research_ids:
- if research_id:
- new_uuid = str(
- uuid.uuid5(
- uuid.NAMESPACE_OID, f"research_{research_id}"
- )
- )
- cursor.execute(
- "UPDATE model_usage SET uuid_research_id = ? WHERE research_id = ?",
- (new_uuid, research_id),
- )
-
- logger.info(
- f"Migrated {len(research_ids)} research IDs in model_usage"
- )
-
- # Search calls table
- cursor.execute("PRAGMA table_info(search_calls)")
- columns = cursor.fetchall()
- has_uuid_research_id = any(
- col[1] == "uuid_research_id" for col in columns
- )
-
- if not has_uuid_research_id:
- cursor.execute(
- "ALTER TABLE search_calls ADD COLUMN uuid_research_id TEXT"
- )
-
- cursor.execute(
- "SELECT DISTINCT research_id FROM search_calls WHERE research_id IS NOT NULL"
- )
- research_ids = cursor.fetchall()
-
- for (research_id,) in research_ids:
- if research_id:
- new_uuid = str(
- uuid.uuid5(
- uuid.NAMESPACE_OID, f"research_{research_id}"
- )
- )
- cursor.execute(
- "UPDATE search_calls SET uuid_research_id = ? WHERE research_id = ?",
- (new_uuid, research_id),
- )
-
- logger.info(
- f"Migrated {len(research_ids)} research IDs in search_calls"
- )
-
- # 3. Migrate benchmark tables
- logger.info("Migrating benchmark tables...")
-
- # Check if benchmark_results table exists
- cursor.execute(
- "SELECT name FROM sqlite_master WHERE type='table' AND name='benchmark_results'"
- )
- if cursor.fetchone():
- cursor.execute("PRAGMA table_info(benchmark_results)")
- columns = cursor.fetchall()
- has_uuid_research_id = any(
- col[1] == "uuid_research_id" for col in columns
- )
-
- if not has_uuid_research_id:
- cursor.execute(
- "ALTER TABLE benchmark_results ADD COLUMN uuid_research_id TEXT"
- )
-
- cursor.execute(
- "SELECT DISTINCT research_id FROM benchmark_results WHERE research_id IS NOT NULL"
- )
- research_ids = cursor.fetchall()
-
- for (research_id,) in research_ids:
- if research_id:
- new_uuid = str(
- uuid.uuid5(
- uuid.NAMESPACE_OID, f"research_{research_id}"
- )
- )
- cursor.execute(
- "UPDATE benchmark_results SET uuid_research_id = ? WHERE research_id = ?",
- (new_uuid, research_id),
- )
-
- logger.info(
- f"Migrated {len(research_ids)} research IDs in benchmark_results"
- )
-
- # Commit all changes
- conn.commit()
- logger.info("UUID migration completed successfully!")
-
- # Note: We're keeping both old and new columns for now
- # The application will use the new UUID columns
- # Old columns can be dropped in a future migration once everything is stable
-
- except Exception as e:
- logger.error(f"Error during UUID migration: {e}")
- conn.rollback()
- raise
- finally:
- conn.execute("PRAGMA foreign_keys = ON") # Re-enable FK constraints
- conn.close()
-
-
-def cleanup_old_columns():
- """
- Cleanup migration - drops old integer columns after UUID migration is stable.
- Run this only after confirming the UUID migration is working correctly.
- """
- logger.warning(
- "This will permanently remove old integer research_id columns!"
- )
- logger.warning("Make sure to backup your database before running this!")
-
- db_path = get_database_path()
- conn = sqlite3.connect(db_path)
- conn.execute("PRAGMA foreign_keys = OFF")
-
- try:
- # For SQLite, we need to recreate tables to drop columns
- # This is complex, so we'll leave old columns for now
- # They can be cleaned up manually if needed
-
- logger.info("Cleanup deferred - old columns remain for safety")
-
- finally:
- conn.execute("PRAGMA foreign_keys = ON")
- conn.close()
-
-
if __name__ == "__main__":
migrate_to_uuid()
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index bf1c4e7019..17ec1a6814 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -38,85 +38,6 @@ def get_db_connection():
return conn
-def init_db():
- """Initialize the database with necessary tables."""
- conn = get_db_connection()
- cursor = conn.cursor()
-
- # Create a dedicated table for research logs
- cursor.execute(
- """
- CREATE TABLE IF NOT EXISTS research_logs (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- research_id INTEGER NOT NULL,
- timestamp TEXT NOT NULL,
- message TEXT NOT NULL,
- log_type TEXT NOT NULL,
- progress INTEGER,
- metadata TEXT,
- FOREIGN KEY (research_id) REFERENCES research_history (id) ON DELETE CASCADE
- )
- """
- )
-
- # Create a dedicated table for research resources
- cursor.execute(
- """
- CREATE TABLE IF NOT EXISTS research_resources (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- research_id INTEGER NOT NULL,
- title TEXT,
- url TEXT,
- content_preview TEXT,
- source_type TEXT,
- metadata TEXT,
- created_at TEXT NOT NULL,
- FOREIGN KEY (research_id) REFERENCES research_history (id) ON DELETE CASCADE
- )
- """
- )
-
- # Check if the duration_seconds column exists, add it if missing
- cursor.execute("PRAGMA table_info(research_history)")
- columns = [column[1] for column in cursor.fetchall()]
-
- if "duration_seconds" not in columns:
- logger.info(
- "Adding missing 'duration_seconds' column to research_history table"
- )
- cursor.execute(
- "ALTER TABLE research_history ADD COLUMN duration_seconds INTEGER"
- )
-
- # Check if the progress column exists, add it if missing
- if "progress" not in columns:
- logger.info(
- "Adding missing 'progress' column to research_history table"
- )
- cursor.execute(
- "ALTER TABLE research_history ADD COLUMN progress INTEGER"
- )
-
- # Check if the title column exists, add it if missing
- if "title" not in columns:
- logger.info("Adding missing 'title' column to research_history table")
- cursor.execute("ALTER TABLE research_history ADD COLUMN title TEXT")
-
- # Check if the metadata column exists, and rename it to "research_meta"
- # if it does.
- if "metadata" in columns:
- logger.info("Renaming 'metadata' column to 'research_meta'")
- cursor.execute(
- "ALTER TABLE research_history RENAME COLUMN metadata TO research_meta"
- )
-
- # Enable foreign key support
- cursor.execute("PRAGMA foreign_keys = ON")
-
- conn.commit()
- conn.close()
-
-
def calculate_duration(created_at_str, completed_at_str=None):
"""
Calculate duration in seconds between created_at timestamp and completed_at or now.
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 5945e45735..d88e1ef4c6 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -16,16 +16,17 @@ from flask import (
from flask_wtf.csrf import generate_csrf
from loguru import logger
-from ...utilities.db_utils import get_db_setting, get_db_session
+from ...utilities.db_utils import (
+ get_db_setting,
+ get_db_session,
+ get_settings_manager,
+)
from ...utilities.url_utils import normalize_url
from ..database.models import Setting, SettingType
from ..services.settings_service import (
create_or_update_setting,
- get_setting,
- get_settings_manager,
set_setting,
)
-from ..services.settings_manager import SettingsManager
from ..utils.templates import render_template_with_defaults
# Create a Blueprint for settings
@@ -37,20 +38,15 @@ def calculate_warnings():
warnings = []
try:
- # Get a fresh database session for safety
- db_session = get_db_session()
-
# Get current settings
- provider = get_setting("llm.provider", "ollama", db_session).lower()
- local_context = get_setting(
- "llm.local_context_window_size", 4096, db_session
- )
+ provider = get_db_setting("llm.provider", "ollama").lower()
+ local_context = get_db_setting("llm.local_context_window_size", 4096)
logger.debug(f"Starting warning calculation - provider={provider}")
# Get dismissal settings
- dismiss_high_context = get_setting(
- "app.warnings.dismiss_high_context", False, db_session
+ dismiss_high_context = get_db_setting(
+ "app.warnings.dismiss_high_context", False
)
# Check warning conditions
@@ -78,15 +74,15 @@ def calculate_warnings():
)
# Get additional warning settings
- dismiss_model_mismatch = get_setting(
- "app.warnings.dismiss_model_mismatch", False, db_session
+ dismiss_model_mismatch = get_db_setting(
+ "app.warnings.dismiss_model_mismatch", False
)
# Get current strategy and model (these need to be passed from the frontend or retrieved differently)
# For now, we'll implement basic warnings that don't require form state
# Model mismatch warning (simplified - checking setting instead of form value)
- current_model = get_setting("llm.model", "", db_session)
+ current_model = get_db_setting("llm.model", "")
if (
current_model
and "70b" in current_model.lower()
@@ -165,7 +161,7 @@ def save_all_settings():
"""Handle saving all settings at once from the unified settings page"""
db_session = get_db_session()
# Get the settings manager but we don't need to assign it to a variable right now
- # get_settings_manager(db_session)
+ # get_db_settings_manager(db_session)
try:
# Process JSON data
@@ -462,7 +458,7 @@ def reset_to_defaults():
# Import default settings from files
try:
# Create settings manager for the temporary config
- settings_mgr = get_settings_manager(db_session)
+ settings_mgr = get_settings_manager()
# Import settings from default files
settings_mgr.load_from_defaults_file()
@@ -499,7 +495,7 @@ def api_get_all_settings():
# Create settings manager
db_session = get_db_session()
- settings_manager = get_settings_manager(db_session)
+ settings_manager = get_settings_manager()
# Get settings
settings = settings_manager.get_all_settings()
@@ -527,15 +523,15 @@ def api_get_all_settings():
@settings_bp.route("/api/<path:key>", methods=["GET"])
-def api_get_setting(key):
+def api_get_db_setting(key):
"""Get a specific setting by key"""
try:
db_session = get_db_session()
# No need to assign if not used
- # get_settings_manager(db_session)
+ # get_db_settings_manager(db_session)
# Get setting
- value = get_setting(key)
+ value = get_db_setting(key)
if value is None:
return jsonify({"error": f"Setting not found: {key}"}), 404
@@ -587,7 +583,7 @@ def api_update_setting(key):
# Get DB session and settings manager
db_session = get_db_session()
# Only use settings_manager if needed - we don't need to assign if not used
- # get_settings_manager(db_session)
+ # get_db_settings_manager(db_session)
# Check if setting exists
db_setting = (
@@ -687,7 +683,7 @@ def api_delete_setting(key):
"""Delete a setting"""
try:
db_session = get_db_session()
- settings_manager = get_settings_manager(db_session)
+ settings_manager = get_settings_manager()
# Check if setting exists
db_setting = (
@@ -711,7 +707,7 @@ def api_delete_setting(key):
def api_import_settings():
"""Import settings from defaults file"""
try:
- settings_manager = get_settings_manager(get_db_session())
+ settings_manager = get_settings_manager()
success = settings_manager.load_from_defaults_file()
@@ -782,7 +778,7 @@ def api_get_available_models():
try:
from datetime import datetime, timedelta
from ..database.models import ProviderModel
- from flask import request, current_app
+ from flask import request
# Check if force_refresh is requested
force_refresh = (
@@ -806,17 +802,16 @@ def api_get_available_models():
# Check database cache first (unless force_refresh is True)
if not force_refresh:
try:
- db_session = current_app.db_session
-
# Define cache expiration (24 hours)
cache_expiry = datetime.utcnow() - timedelta(hours=24)
# Get cached models from database
- cached_models = (
- db_session.query(ProviderModel)
- .filter(ProviderModel.last_updated > cache_expiry)
- .all()
- )
+ with get_db_session("settings_routes") as db_session:
+ cached_models = (
+ db_session.query(ProviderModel)
+ .filter(ProviderModel.last_updated > cache_expiry)
+ .all()
+ )
if cached_models:
logger.info(
@@ -1269,41 +1264,44 @@ def api_get_available_models():
# Save fetched models to database cache
if force_refresh or providers:
# We fetched fresh data, save it to database
- try:
- from datetime import datetime
-
- db_session = current_app.db_session
-
- # Clear old cache entries for providers we're updating
- for provider_key in providers.keys():
- provider_name = provider_key.replace("_models", "").upper()
- db_session.query(ProviderModel).filter(
- ProviderModel.provider == provider_name
- ).delete()
-
- # Insert new models
- for provider_key, models in providers.items():
- provider_name = provider_key.replace("_models", "").upper()
- for model in models:
- if (
- isinstance(model, dict)
- and "value" in model
- and "label" in model
- ):
- new_model = ProviderModel(
- provider=provider_name,
- model_key=model["value"],
- model_label=model["label"],
- last_updated=datetime.utcnow(),
- )
- db_session.add(new_model)
-
- db_session.commit()
- logger.info("Successfully cached models to database")
-
- except Exception:
- logger.exception("Error saving models to database cache")
- db_session.rollback()
+ with get_db_session("settings_routes") as db_session:
+ try:
+ from datetime import datetime
+
+ # Clear old cache entries for providers we're updating
+ for provider_key in providers.keys():
+ provider_name = provider_key.replace(
+ "_models", ""
+ ).upper()
+ db_session.query(ProviderModel).filter(
+ ProviderModel.provider == provider_name
+ ).delete()
+
+ # Insert new models
+ for provider_key, models in providers.items():
+ provider_name = provider_key.replace(
+ "_models", ""
+ ).upper()
+ for model in models:
+ if (
+ isinstance(model, dict)
+ and "value" in model
+ and "label" in model
+ ):
+ new_model = ProviderModel(
+ provider=provider_name,
+ model_key=model["value"],
+ model_label=model["label"],
+ last_updated=datetime.utcnow(),
+ )
+ db_session.add(new_model)
+
+ db_session.commit()
+ logger.info("Successfully cached models to database")
+
+ except Exception:
+ logger.exception("Error saving models to database cache")
+ db_session.rollback()
# Return all options
return jsonify(
@@ -1858,9 +1856,9 @@ def api_get_rate_limiting_status():
"max_wait_seconds": round(max_wait, 2),
"last_updated": last_updated,
"total_attempts": total_attempts,
- "success_rate": round(success_rate * 100, 1)
- if success_rate
- else 0.0,
+ "success_rate": (
+ round(success_rate * 100, 1) if success_rate else 0.0
+ ),
}
)
@@ -1934,12 +1932,11 @@ def get_bulk_settings():
# Fetch all settings at once
session = get_db_session()
- settings_manager = SettingsManager(db_session=session)
result = {}
for key in requested:
try:
- value = settings_manager.get_setting(key)
+ value = get_db_setting(key)
result[key] = {"value": value, "exists": value is not None}
except Exception as e:
logger.warning(f"Error getting setting {key}: {e}")
diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.py
index 87386c83f4..32b1a13b58 100644
--- a/src/local_deep_research/web/services/settings_manager.py
+++ b/src/local_deep_research/web/services/settings_manager.py
@@ -66,11 +66,17 @@ class SettingsManager:
self.db_session = db_session
self.db_first = True # Always prioritize DB settings
- # Load default settings.
+ @property
+ def default_settings(self) -> Dict[str, Any]:
+ """
+ Returns:
+ The default settings, loaded from JSON.
+
+ """
default_settings = pkg_resources.read_text(
defaults, "default_settings.json"
)
- self.default_settings = json.loads(default_settings)
+ return json.loads(default_settings)
def __get_typed_setting_value(
self,
@@ -462,27 +468,6 @@ class SettingsManager:
self.db_session.add(version)
self.db_session.commit()
- @classmethod
- def get_instance(
- cls, db_session: Optional[Session] = None
- ) -> "SettingsManager":
- """
- Get a singleton instance of the settings manager
-
- Args:
- db_session: Optional database session
-
- Returns:
- SettingsManager instance
- """
- if not hasattr(cls, "_instance"):
- cls._instance = cls(db_session)
- elif db_session and not cls._instance.db_session:
- # Update existing instance with a session
- cls._instance.db_session = db_session
-
- return cls._instance
-
def import_settings(
self,
settings_data: Dict[str, Any],
@@ -517,6 +502,11 @@ class SettingsManager:
setting = Setting(key=key, **setting_values)
self.db_session.add(setting)
+ if commit or delete_extra:
+ self.db_session.commit()
+ # Emit WebSocket event for all imported settings
+ self._emit_settings_changed(list(settings_data.keys()))
+
if delete_extra:
all_settings = self.get_all_settings()
for key in all_settings:
@@ -524,11 +514,6 @@ class SettingsManager:
logger.debug(f"Deleting extraneous setting: {key}")
self.delete_setting(key, commit=False)
- if commit:
- self.db_session.commit()
- # Emit WebSocket event for all imported settings
- self._emit_settings_changed(list(settings_data.keys()))
-
def _create_setting(self, key, value, setting_type):
"""Create a setting with appropriate metadata"""
diff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.py
index d54c47e524..5bc9def4b1 100644
--- a/src/local_deep_research/web/services/settings_service.py
+++ b/src/local_deep_research/web/services/settings_service.py
@@ -3,41 +3,10 @@ from typing import Any, Dict, Optional, Union
from loguru import logger
from ..database.models import Setting
-from .settings_manager import SettingsManager
+from ...utilities.db_utils import get_settings_manager
-def get_settings_manager(db_session=None):
- """
- Get or create the settings manager instance.
-
- Args:
- db_session: Optional database session to use
-
- Returns:
- SettingsManager: The settings manager instance
- """
- return SettingsManager.get_instance(db_session)
-
-
-def get_setting(key: str, default: Any = None, db_session=None) -> Any:
- """
- Get a setting value by key
-
- Args:
- key: Setting key
- default: Default value if setting not found
- db_session: Optional database session to use
-
- Returns:
- Any: The setting value
- """
- manager = get_settings_manager(db_session)
- return manager.get_setting(key, default)
-
-
-def set_setting(
- key: str, value: Any, commit: bool = True, db_session=None
-) -> bool:
+def set_setting(key: str, value: Any, commit: bool = True) -> bool:
"""
Set a setting value
@@ -45,26 +14,23 @@ def set_setting(
key: Setting key
value: Setting value
commit: Whether to commit the change
- db_session: Optional database session
Returns:
bool: True if successful
"""
- manager = get_settings_manager(db_session)
+ manager = get_settings_manager()
return manager.set_setting(key, value, commit)
-def get_all_settings(db_session=None) -> Dict[str, Any]:
+def get_all_settings() -> Dict[str, Any]:
"""
Get all settings, optionally filtered by type
- Args:
- db_session: Optional database session
-
Returns:
Dict[str, Any]: Dictionary of settings
+
"""
- manager = get_settings_manager(db_session)
+ manager = get_settings_manager()
return manager.get_all_settings()
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index a815a6fdd6..fe6a1e30d9 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -9,7 +9,7 @@ from collections import deque
from typing import Dict, Optional, Tuple, List
-from ...utilities.db_utils import get_db_session
+from ...utilities.db_utils import get_db_session, get_db_setting
from ...web.database.models import RateLimitAttempt, RateLimitEstimate
logger = logging.getLogger(__name__)
@@ -23,8 +23,6 @@ class AdaptiveRateLimitTracker:
def __init__(self):
# Load configuration from database settings
- from ...utilities.db_utils import get_db_setting
-
self.memory_window = int(
get_db_setting("rate_limiting.memory_window", 100)
)
diff --git a/tests/conftest.py b/tests/conftest.py
index 8375bb8162..166d4d3fd8 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -112,7 +112,6 @@ def setup_database_for_all_tests(
# Clear caches and patch
db_utils_module.get_db_session.cache_clear()
- db_utils_module.get_settings_manager.cache_clear()
mock_get_db_session = session_mocker.patch(
"src.local_deep_research.utilities.db_utils.get_db_session"
diff --git a/tests/rate_limiting/test_rate_limiting.py b/tests/rate_limiting/test_rate_limiting.py
index 33d72b6145..2cd902ba8c 100644
--- a/tests/rate_limiting/test_rate_limiting.py
+++ b/tests/rate_limiting/test_rate_limiting.py
@@ -14,8 +14,10 @@ from src.local_deep_research.web_search_engines.rate_limiting import (
AdaptiveRateLimitTracker,
RateLimitError,
)
-from src.local_deep_research.utilities.db_utils import DB_PATH
-from src.local_deep_research.web.database.schema_upgrade import (
+from src.local_deep_research.utilities.db_utils import (
+ DB_PATH,
+)
+from local_deep_research.web.database.migrations import (
create_rate_limiting_tables,
)
@@ -34,7 +36,15 @@ class TestAdaptiveRateLimitTracker(unittest.TestCase):
"""Set up test fixtures."""
# Note: Using the main database - in a real test environment
# you'd want to mock the database session
- self.tracker = AdaptiveRateLimitTracker()
+
+ # Force settings manager to use default settings instead of reading
+ # from the DB. This makes things more reliable.
+ with patch(
+ "src.local_deep_research.web_search_engines.rate_limiting.tracker"
+ ".get_db_setting",
+ side_effect=lambda key, default=None: default,
+ ):
+ self.tracker = AdaptiveRateLimitTracker()
# Skip database cleanup in CI to avoid timeouts
if os.environ.get("CI") != "true":
diff --git a/tests/test_settings_manager.py b/tests/test_settings_manager.py
index 2f31013406..82406ca314 100644
--- a/tests/test_settings_manager.py
+++ b/tests/test_settings_manager.py
@@ -10,9 +10,7 @@ from src.local_deep_research.web.services.settings_manager import (
SettingType,
check_env_setting,
)
-from src.local_deep_research.web.services.settings_service import (
- get_setting as get_app_setting,
-)
+from src.local_deep_research.utilities.db_utils import get_db_setting
def test_check_env_setting_exists(monkeypatch):
@@ -245,8 +243,8 @@ def test_app_get_setting_from_real_db(
"LDR_APP_VERSION", raising=False
) # Ensure no env override
- # Call the get_setting function from settings_service
- value = get_app_setting("test.app.version.get", db_session=session)
+ # Check that the value was saved.
+ value = get_db_setting("test.app.version.get")
assert value == "1.0.0"
session.close() # Close the session for this test