~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Fix broken database migration system (issue #638) (#646)
LearningCircuit6c9334887392
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 06a472c8c5..85ca47c12c 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -42,6 +42,7 @@ jobs:tests/test_wikipedia_url_security.py \tests/test_search_engines_enhanced.py \tests/test_utils.py \+ tests/test_database_initialization.py \tests/rate_limiting/ \tests/retriever_integration/ \tests/feature_tests/ \diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex efcdbec68e..0ca27cfdb4 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -286,9 +286,17 @@ class DatabaseManager:# Store connectionself.connections[username] = engine- # Ensure all tables exist (for completeness during creation)- # Tables are created by Base.metadata.create_all() above- # Future migrations will be handled by Alembic+ # Initialize database tables using centralized initialization+ from .initialize import initialize_database++ try:+ # Create a session for settings initialization+ Session = sessionmaker(bind=engine)+ with Session() as session:+ initialize_database(engine, session)+ except Exception as e:+ logger.warning(f"Could not initialize database fully: {e}")+ # Still continue - basic tables were created abovelogger.info(f"Created encrypted database for user {username}")return enginediff --git a/src/local_deep_research/database/initialize.py b/src/local_deep_research/database/initialize.pynew file mode 100644index 0000000000..172c6ff038--- /dev/null+++ b/src/local_deep_research/database/initialize.py@@ -0,0 +1,127 @@+"""+Centralized database initialization module.++This module provides a single entry point for database initialization.+In the future, this will be replaced with Alembic migrations for better+version control and schema evolution.++TODO: Implement Alembic migrations for production use+"""++from typing import Optional+from loguru import logger+from sqlalchemy import Engine, inspect+from sqlalchemy.orm import Session++from ..database.models import Base+++def initialize_database(+ engine: Engine,+ db_session: Optional[Session] = None,+) -> None:+ """+ Initialize database tables if they don't exist.++ This is a temporary solution until Alembic migrations are implemented.+ Currently creates all tables defined in the models if they don't exist.++ Args:+ engine: SQLAlchemy engine for the database+ db_session: Optional database session for settings initialization+ """+ inspector = inspect(engine)+ existing_tables = inspector.get_table_names()++ logger.info(+ f"Initializing database with {len(existing_tables)} existing tables"+ )+ logger.debug(+ f"Base.metadata has {len(Base.metadata.tables)} tables defined"+ )++ # Create all tables (including news tables) - let SQLAlchemy handle dependencies+ # checkfirst=True ensures existing tables are not recreated+ logger.info("Creating database tables")+ Base.metadata.create_all(engine, checkfirst=True)++ # Check what was created (need new inspector to avoid caching)+ new_inspector = inspect(engine)+ new_tables = new_inspector.get_table_names()+ logger.info(f"After initialization: {len(new_tables)} tables exist")++ # Initialize default settings if session provided+ if db_session:+ try:+ _initialize_default_settings(db_session)+ except Exception as e:+ logger.warning(f"Could not initialize default settings: {e}")++ logger.info("Database initialization complete")+++def _initialize_default_settings(db_session: Session) -> None:+ """+ Initialize default settings from the defaults file.++ Args:+ db_session: Database session to use for settings initialization+ """+ from ..web.services.settings_manager import SettingsManager++ try:+ settings_mgr = SettingsManager(db_session)++ # Check if we need to update settings+ if settings_mgr.db_version_matches_package():+ logger.debug("Settings version matches package, skipping update")+ return++ logger.info("Loading default settings into database")++ # Load settings from defaults file+ # This will not overwrite existing settings but will add new ones+ settings_mgr.load_from_defaults_file(overwrite=False, delete_extra=True)++ # Update the saved version+ settings_mgr.update_db_version()++ logger.info("Default settings initialized successfully")++ except Exception:+ logger.exception("Error initializing default settings")+++def check_database_schema(engine: Engine) -> dict:+ """+ Check the current database schema and return information about tables.++ Args:+ engine: SQLAlchemy engine for the database++ Returns:+ Dictionary with schema information including tables and their columns+ """+ inspector = inspect(engine)+ schema_info = {+ "tables": {},+ "missing_tables": [],+ "has_news_tables": False,+ }++ # Check core tables+ for table_name in Base.metadata.tables.keys():+ if inspector.has_table(table_name):+ columns = [col["name"] for col in inspector.get_columns(table_name)]+ schema_info["tables"][table_name] = columns+ else:+ schema_info["missing_tables"].append(table_name)++ # Check if news tables exist+ news_tables = ["news_subscription", "news_card", "news_interest"]+ for table_name in news_tables:+ if table_name in schema_info["tables"]:+ schema_info["has_news_tables"] = True+ break++ return schema_infodiff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.pydeleted file mode 100644index 7a4ea905bc..0000000000--- a/src/local_deep_research/web/database/migrations.py+++ /dev/null@@ -1,144 +0,0 @@-from loguru import logger-from sqlalchemy import inspect--from ..services.settings_manager import SettingsManager-from .models import (- Base,- Journal,- Setting,- ResearchLog,- Research,- ResearchHistory,-)--# Import news models for table creation-try:- from ...news.models import (- BaseSubscription,- SubscriptionFolder,- UserPreference,- Rating,- NewsCard,- CardVersion,- )-- NEWS_MODELS_AVAILABLE = True-except ImportError:- NEWS_MODELS_AVAILABLE = False- logger.warning(- "News models not available - news tables will not be created"- )---def import_default_settings_file(db_session):- """- Imports all settings from the default settings file to the DB.- """- settings_mgr = SettingsManager(db_session)- if settings_mgr.db_version_matches_package():- # We probably shouldn't bother loading settings if the version didn't- # change.- return- logger.info("Detected a new version of default settings, upgrading DB.")-- # Create settings manager and import settings- try:- # This will not overwrite existing settings, but will delete- # extraneous ones. This should be enough to update anyone with- # old versions of the settings.- settings_mgr.load_from_defaults_file(overwrite=False, delete_extra=True)- logger.info("Successfully imported settings from files")-- # Update the saved version.- settings_mgr.update_db_version()- except Exception as e:- logger.exception("Error importing settings from files: %s", e)---def run_migrations(engine, db_session=None):- """- Run any necessary database migrations-- Args:- engine: SQLAlchemy engine- db_session: Optional SQLAlchemy session- """- # Create all tables if they don't exist- inspector = inspect(engine)- if not inspector.has_table("settings"):- logger.info("Creating settings table")- Base.metadata.create_all(engine, tables=[Setting.__table__])-- if not inspector.has_table(Journal.__tablename__):- logger.info("Creating journals table.")- Base.metadata.create_all(engine, tables=[Journal.__table__])-- if not inspector.has_table(ResearchLog.__tablename__):- logger.info("Creating research logs table.")- Base.metadata.create_all(engine, tables=[ResearchLog.__table__])-- if not inspector.has_table(Research.__tablename__):- logger.info("Creating research table.")- Base.metadata.create_all(engine, tables=[Research.__table__])-- if not inspector.has_table(ResearchHistory.__tablename__):- logger.info("Creating research table.")- Base.metadata.create_all(engine, tables=[ResearchHistory.__table__])-- # Create news tables if available- if NEWS_MODELS_AVAILABLE:- from ...utilities.db_utils import get_db_setting-- # Check if news is enabled (default to True)- news_enabled = True- if db_session:- try:- news_enabled = get_db_setting(- "news.enabled", True, db_session=db_session- )- except Exception:- # If we can't check the setting, default to enabled- news_enabled = True-- if news_enabled:- # Import the news Base to ensure proper metadata- from ...news.models import Base as NewsBase-- # Create news tables if they don't exist- if not inspector.has_table("news_subscriptions"):- logger.info("Creating news_subscriptions table")- NewsBase.metadata.create_all(- engine, tables=[BaseSubscription.__table__]- )-- if not inspector.has_table("news_subscription_folders"):- logger.info("Creating news_subscription_folders table")- NewsBase.metadata.create_all(- engine, tables=[SubscriptionFolder.__table__]- )-- if not inspector.has_table("news_user_preferences"):- logger.info("Creating news_user_preferences table")- NewsBase.metadata.create_all(- engine, tables=[UserPreference.__table__]- )-- if not inspector.has_table("news_ratings"):- logger.info("Creating news_ratings table")- NewsBase.metadata.create_all(engine, tables=[Rating.__table__])-- if not inspector.has_table("news_cards"):- logger.info("Creating news_cards table")- NewsBase.metadata.create_all(- engine, tables=[NewsCard.__table__]- )-- if not inspector.has_table("news_card_versions"):- logger.info("Creating news_card_versions table")- NewsBase.metadata.create_all(- engine, tables=[CardVersion.__table__]- )-- # Import existing settings from files- if db_session:- import_default_settings_file(db_session)diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 6fd0c6e017..088d7fadcc 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -493,15 +493,6 @@ def reset_to_defaults():except Exception:logger.exception("Error importing default settings")- # Fallback to predefined settings if file import fails- logger.info("Falling back to predefined settings")- # Import here to avoid circular imports- from ..database.migrations import (- setup_predefined_settings as setup_settings,- )-- setup_settings(db_session)-# Return successreturn jsonify({diff --git a/tests/test_database_initialization.py b/tests/test_database_initialization.pynew file mode 100644index 0000000000..35e5532fe1--- /dev/null+++ b/tests/test_database_initialization.py@@ -0,0 +1,165 @@+"""Test database initialization module"""++import os+import tempfile+import pytest+from sqlalchemy import create_engine, inspect+from sqlalchemy.orm import sessionmaker++from local_deep_research.database.initialize import (+ initialize_database,+ check_database_schema,+)+from local_deep_research.database.models import (+ Setting,+)+++class TestDatabaseInitialization:+ """Test the centralized database initialization"""++ @pytest.fixture+ def temp_db(self):+ """Create a temporary database for testing"""+ with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as tmp:+ db_path = tmp.name++ engine = create_engine(f"sqlite:///{db_path}")+ yield engine, db_path++ # Cleanup+ engine.dispose()+ if os.path.exists(db_path):+ os.unlink(db_path)++ def test_initialize_core_tables(self, temp_db):+ """Test that core tables are created correctly"""+ engine, db_path = temp_db++ # Initialize database+ Session = sessionmaker(bind=engine)+ with Session() as session:+ initialize_database(engine, session)++ # Check that core tables exist+ inspector = inspect(engine)+ tables = inspector.get_table_names()++ # Verify essential tables+ expected_core_tables = [+ "settings",+ "research",+ "research_history",+ "journals",+ "app_logs", # Correct table name+ "users",+ "queued_researches", # Correct table name+ "search_cache",+ "token_usage",+ "research_ratings",+ ]++ for table in expected_core_tables:+ assert table in tables, f"Table '{table}' should exist"++ def test_initialize_with_news_tables(self, temp_db):+ """Test that news tables are created when requested"""+ engine, db_path = temp_db++ # Initialize database with news tables+ Session = sessionmaker(bind=engine)+ with Session() as session:+ initialize_database(engine, session)++ # Check schema+ schema_info = check_database_schema(engine)++ # News tables might not be available if the news module isn't imported+ # Just check that initialization doesn't fail+ assert len(schema_info["tables"]) > 0+ assert len(schema_info["missing_tables"]) == 0++ def test_idempotent_initialization(self, temp_db):+ """Test that initialization is idempotent (can be run multiple times)"""+ engine, db_path = temp_db+ Session = sessionmaker(bind=engine)++ # Initialize twice+ with Session() as session:+ initialize_database(engine, session)++ # Get initial table count+ inspector = inspect(engine)+ initial_tables = set(inspector.get_table_names())++ # Initialize again+ with Session() as session:+ initialize_database(engine, session)++ # Check that no duplicate tables were created+ final_tables = set(inspector.get_table_names())+ assert initial_tables == final_tables++ def test_check_database_schema(self, temp_db):+ """Test the schema checking function"""+ engine, db_path = temp_db++ # Check schema before initialization+ schema_info = check_database_schema(engine)+ assert len(schema_info["tables"]) == 0+ assert len(schema_info["missing_tables"]) > 0++ # Initialize database+ Session = sessionmaker(bind=engine)+ with Session() as session:+ initialize_database(engine, session)++ # Check schema after initialization+ schema_info = check_database_schema(engine)+ assert len(schema_info["tables"]) > 0+ assert len(schema_info["missing_tables"]) == 0++ def test_settings_initialization(self, temp_db):+ """Test that settings can be initialized"""+ engine, db_path = temp_db++ # Initialize database with settings+ Session = sessionmaker(bind=engine)+ with Session() as session:+ initialize_database(engine, session)++ # Check if settings table is queryable+ count = session.query(Setting).count()+ assert count >= 0 # Should not raise an error++ def test_partial_table_creation(self, temp_db):+ """Test that initialization completes even with existing tables"""+ engine, db_path = temp_db++ # Create only one table manually (Setting has no foreign keys)+ from local_deep_research.database.models import Setting++ Setting.__table__.create(engine)++ # Verify only that table exists+ inspector = inspect(engine)+ initial_tables = inspector.get_table_names()+ assert "settings" in initial_tables+ assert len(initial_tables) == 1 # Only settings table++ # Initialize database (should create all missing tables)+ Session = sessionmaker(bind=engine)+ with Session() as session:+ initialize_database(engine, session)++ # Verify many more tables now exist (need fresh inspector)+ final_inspector = inspect(engine)+ final_tables = final_inspector.get_table_names()+ assert "settings" in final_tables # Original table still there+ assert len(final_tables) > 20 # Many more tables created++ # Verify some key tables+ assert "research" in final_tables+ assert "journals" in final_tables+ assert "app_logs" in final_tables+ assert "token_usage" in final_tables