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.

refactor: Replace legacy get_db_session with get_user_db_session

LearningCircuita916a971cc15
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index 55605048f2..0044f418c1 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -5,7 +5,7 @@ from loguru import logger
from ...config.paths import get_data_directory, get_database_path
from ...database.models import ResearchLog
-from ...utilities.db_utils import get_db_session
+from ...database.session_context import get_user_db_session
# Database paths using new centralized configuration
DATA_DIR = get_data_directory()
@@ -139,27 +139,27 @@ def get_logs_for_research(research_id):
List of log entries as dictionaries
"""
try:
- session = get_db_session()
- log_results = (
- session.query(ResearchLog)
- .filter(ResearchLog.research_id == research_id)
- .order_by(ResearchLog.timestamp.asc())
- .all()
- )
+ with get_user_db_session() as session:
+ log_results = (
+ session.query(ResearchLog)
+ .filter(ResearchLog.research_id == research_id)
+ .order_by(ResearchLog.timestamp.asc())
+ .all()
+ )
- logs = []
- for result in log_results:
- # Convert entry for frontend consumption
- formatted_entry = {
- "time": result.timestamp,
- "message": result.message,
- "type": result.level,
- "module": result.module,
- "line_no": result.line_no,
- }
- logs.append(formatted_entry)
-
- return logs
+ logs = []
+ for result in log_results:
+ # Convert entry for frontend consumption
+ formatted_entry = {
+ "time": result.timestamp,
+ "message": result.message,
+ "type": result.level,
+ "module": result.module,
+ "line_no": result.line_no,
+ }
+ logs.append(formatted_entry)
+
+ return logs
except Exception:
logger.exception("Error retrieving logs from database")
return []
@@ -176,10 +176,10 @@ def get_total_logs_for_research(research_id):
Returns:
int: Total number of logs for the specified research ID.
"""
- session = get_db_session()
- total_logs = (
- session.query(ResearchLog)
- .filter(ResearchLog.research_id == research_id)
- .count()
- )
- return total_logs
+ with get_user_db_session() as session:
+ total_logs = (
+ session.query(ResearchLog)
+ .filter(ResearchLog.research_id == research_id)
+ .count()
+ )
+ return total_logs
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 71c18e1b3e..ae6e10a404 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -9,7 +9,7 @@ from loguru import logger
from datetime import datetime, UTC
from ...database.models import ResearchHistory
-from ...utilities.db_utils import get_db_session
+from ...database.session_context import get_user_db_session
from ...utilities.url_utils import normalize_url
from ..auth.decorators import login_required
from ..routes.research_routes import active_research, termination_flags
@@ -34,8 +34,8 @@ api_bp = Blueprint("api", __name__)
def get_current_config():
"""Get the current configuration from database settings."""
try:
- session = get_db_session()
- settings_manager = SettingsManager(session)
+ with get_user_db_session() as session:
+ settings_manager = SettingsManager(session)
config = {
"provider": settings_manager.get_setting(
@@ -92,19 +92,18 @@ def api_start_research():
"search_engine": "searxng", # Default
}
- db_session = get_db_session()
- research = ResearchHistory(
- query=query,
- mode=mode,
- status="in_progress",
- created_at=created_at,
- progress_log=[{"time": created_at, "progress": 0}],
- research_meta=research_settings,
- )
- db_session.add(research)
- db_session.commit()
- research_id = research.id
- db_session.close()
+ with get_user_db_session() as db_session:
+ research = ResearchHistory(
+ query=query,
+ mode=mode,
+ status="in_progress",
+ created_at=created_at,
+ progress_log=[{"time": created_at, "progress": 0}],
+ research_meta=research_settings,
+ )
+ db_session.add(research)
+ db_session.commit()
+ research_id = research.id
# Start the research process
research_thread = start_research_process(
@@ -141,23 +140,13 @@ def api_research_status(research_id):
"""
try:
# Get a fresh session to avoid conflicts with the research process
- from flask import g
-
- from ...database.encrypted_db import db_manager
-
- username = (
- g.current_user
- if hasattr(g, "current_user") and g.current_user
- else None
- )
- if username:
- db_session = db_manager.get_session(username)
- else:
- db_session = get_db_session()
- research = (
- db_session.query(ResearchHistory).filter_by(id=research_id).first()
- )
+ with get_user_db_session() as db_session:
+ research = (
+ db_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
if research is None:
return jsonify({"error": "Research not found"}), 404
@@ -248,11 +237,12 @@ def api_add_resource(research_id):
)
# Check if the research exists
- db_session = get_db_session()
- research = (
- db_session.query(ResearchHistory).filter_by(id=research_id).first()
- )
- db_session.close()
+ with get_user_db_session() as db_session:
+ research = (
+ db_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
if not research:
return jsonify(
diff --git a/src/local_deep_research/web/services/resource_service.py b/src/local_deep_research/web/services/resource_service.py
index 17bc4f8e1c..632b2b4bc4 100644
--- a/src/local_deep_research/web/services/resource_service.py
+++ b/src/local_deep_research/web/services/resource_service.py
@@ -3,7 +3,7 @@ from datetime import datetime, UTC
from loguru import logger
from ...database.models import ResearchResource
-from ...utilities.db_utils import get_db_session
+from ...database.session_context import get_user_db_session
def get_resources_for_research(research_id):
@@ -17,32 +17,30 @@ def get_resources_for_research(research_id):
list: List of resource objects for the research
"""
try:
- db_session = get_db_session()
-
- # Query to get resources for the research
- resources_list = (
- db_session.query(ResearchResource)
- .filter_by(research_id=research_id)
- .order_by(ResearchResource.id.asc())
- .all()
- )
-
- resources = []
- for resource in resources_list:
- resources.append(
- {
- "id": resource.id,
- "research_id": resource.research_id,
- "title": resource.title,
- "url": resource.url,
- "content_preview": resource.content_preview,
- "source_type": resource.source_type,
- "metadata": resource.resource_metadata or {},
- }
+ with get_user_db_session() as db_session:
+ # Query to get resources for the research
+ resources_list = (
+ db_session.query(ResearchResource)
+ .filter_by(research_id=research_id)
+ .order_by(ResearchResource.id.asc())
+ .all()
)
- db_session.close()
- return resources
+ resources = []
+ for resource in resources_list:
+ resources.append(
+ {
+ "id": resource.id,
+ "research_id": resource.research_id,
+ "title": resource.title,
+ "url": resource.url,
+ "content_preview": resource.content_preview,
+ "source_type": resource.source_type,
+ "metadata": resource.resource_metadata or {},
+ }
+ )
+
+ return resources
except Exception as e:
logger.exception(
@@ -66,42 +64,32 @@ def add_resource(
research_id (str): The UUID of the research
title (str): The title of the resource
url (str): The URL of the resource
- content_preview (str, optional): A preview or snippet of the resource content
- source_type (str, optional): The type of resource (web, pdf, etc.)
- metadata (dict, optional): Additional metadata for the resource
+ content_preview (str, optional): A preview of the content
+ source_type (str, optional): The type of source
+ metadata (dict, optional): Additional metadata
Returns:
- int: The ID of the newly created resource
+ ResearchResource: The created resource object
"""
try:
- db_session = get_db_session()
-
- created_at = datetime.now(UTC).isoformat()
-
- resource = ResearchResource(
- research_id=research_id,
- title=title,
- url=url,
- content_preview=content_preview,
- source_type=source_type,
- resource_metadata=metadata,
- created_at=created_at,
- )
+ with get_user_db_session() as db_session:
+ resource = ResearchResource(
+ research_id=research_id,
+ title=title,
+ url=url,
+ content_preview=content_preview,
+ source_type=source_type,
+ resource_metadata=metadata,
+ accessed_at=datetime.now(UTC),
+ )
- db_session.add(resource)
- db_session.commit()
- resource_id = resource.id
- db_session.close()
+ db_session.add(resource)
+ db_session.commit()
- logger.info(
- f"Added resource {resource_id} for research {research_id}: {title}"
- )
- return resource_id
+ return resource
except Exception as e:
- logger.exception(
- f"Error adding resource for research {research_id}: {e!s}"
- )
+ logger.exception(f"Error adding resource: {e!s}")
raise
@@ -113,28 +101,50 @@ def delete_resource(resource_id):
resource_id (int): The ID of the resource to delete
Returns:
- bool: True if the resource was deleted successfully, False otherwise
+ bool: True if deletion was successful
+
+ Raises:
+ ValueError: If resource not found
"""
try:
- db_session = get_db_session()
-
- # First check if the resource exists
- resource = (
- db_session.query(ResearchResource).filter_by(id=resource_id).first()
- )
+ with get_user_db_session() as db_session:
+ # Find the resource
+ resource = (
+ db_session.query(ResearchResource)
+ .filter_by(id=resource_id)
+ .first()
+ )
- if not resource:
- db_session.close()
- return False
+ if not resource:
+ raise ValueError(f"Resource with ID {resource_id} not found")
- # Delete the resource
- db_session.delete(resource)
- db_session.commit()
- db_session.close()
+ db_session.delete(resource)
+ db_session.commit()
- logger.info(f"Deleted resource {resource_id}")
- return True
+ logger.info(f"Deleted resource {resource_id}")
+ return True
+ except ValueError:
+ raise
except Exception as e:
logger.exception(f"Error deleting resource {resource_id}: {e!s}")
raise
+
+
+def update_resource_content(resource_id, content):
+ """Update resource content if needed"""
+ try:
+ with get_user_db_session() as db_session:
+ resource = (
+ db_session.query(ResearchResource)
+ .filter_by(id=resource_id)
+ .first()
+ )
+ if resource:
+ resource.content = content
+ resource.last_fetched = datetime.now(UTC)
+ db_session.commit()
+ return resource
+ except Exception as e:
+ logger.exception(f"Error updating resource content: {e}")
+ return None