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: CASCADE→SET NULL, remove dead SQL views, centralise resource lookups (#2587)

LearningCircuit2033f977e434
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index d42a7fffa0..a2683fb35a 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -180,7 +180,7 @@ class Document(Base):
# Link to original research resource (for research downloads) - nullable for uploads
resource_id = Column(
Integer,
- ForeignKey("research_resources.id", ondelete="CASCADE"),
+ ForeignKey("research_resources.id", ondelete="SET NULL"),
nullable=True,
index=True,
)
diff --git a/src/local_deep_research/database/views/library_views.py b/src/local_deep_research/database/views/library_views.py
deleted file mode 100644
index 1b6c320c57..0000000000
--- a/src/local_deep_research/database/views/library_views.py
+++ /dev/null
@@ -1,245 +0,0 @@
-"""
-Database views for the library system.
-These views combine data from multiple tables for efficient querying.
-"""
-
-from loguru import logger
-from sqlalchemy import text
-from sqlalchemy.orm import Session
-
-
-def create_library_views(session: Session):
- """
- Create database views for the library system.
- These views combine downloaded documents with their classification and research data.
- """
-
- # View that combines Document with all related information
- # DevSkim: ignore DS137138 - SQL patterns 'http://%' are for URL parsing, not insecure URLs
- library_documents_enriched_view = """
- CREATE OR REPLACE VIEW library_documents_enriched AS
- SELECT
- -- Library document fields
- ld.id,
- ld.resource_id,
- ld.research_id,
- ld.document_hash,
- ld.file_path,
- ld.file_size,
- ld.file_type,
- ld.mime_type,
- ld.title as document_title,
- ld.authors,
- ld.published_date,
- ld.doi,
- ld.arxiv_id,
- ld.pmid,
- ld.pmcid,
- ld.download_status,
- ld.downloaded_at,
- ld.favorite,
- ld.tags,
- ld.notes,
-
- -- From ResearchResource
- rr.url as original_url,
- rr.source_type,
- rr.content_preview,
- rr.resource_metadata,
-
- -- Extract domain from URL (DevSkim: ignore DS137138 - URL pattern matching)
- CASE
- WHEN rr.url LIKE 'http://%' THEN -- DevSkim: ignore DS137138
- SUBSTRING(rr.url FROM 'http://([^/]+)') -- DevSkim: ignore DS137138
- WHEN rr.url LIKE 'https://%' THEN
- SUBSTRING(rr.url FROM 'https://([^/]+)')
- ELSE NULL
- END as domain,
-
- -- From ResearchHistory
- rh.title as research_title,
- rh.query as research_query,
- rh.mode as research_mode,
- rh.created_at as research_date,
-
- -- From DomainClassification (if exists)
- dc.category as domain_category,
- dc.subcategory as domain_subcategory,
- dc.confidence as classification_confidence,
-
- -- Special domain flags for filtering
- CASE
- WHEN rr.url LIKE '%arxiv.org%' THEN true
- ELSE false
- END as is_arxiv,
-
- CASE
- WHEN rr.url LIKE '%pubmed%' OR rr.url LIKE '%ncbi.nlm.nih.gov%' THEN true
- ELSE false
- END as is_pubmed,
-
- CASE
- WHEN rr.url LIKE '%semanticscholar.org%' THEN true
- ELSE false
- END as is_semantic_scholar,
-
- CASE
- WHEN ld.doi IS NOT NULL THEN true
- ELSE false
- END as has_doi,
-
- CASE
- WHEN ld.file_type = 'pdf' THEN true
- ELSE false
- END as is_pdf
-
- FROM library_documents ld
- INNER JOIN research_resources rr ON ld.resource_id = rr.id
- INNER JOIN research_history rh ON ld.research_id = rh.id
- LEFT JOIN domain_classifications dc ON
- dc.domain = CASE
- WHEN rr.url LIKE 'http://%' THEN -- DevSkim: ignore DS137138
- SUBSTRING(rr.url FROM 'http://([^/]+)') -- DevSkim: ignore DS137138
- WHEN rr.url LIKE 'https://%' THEN
- SUBSTRING(rr.url FROM 'https://([^/]+)')
- ELSE NULL
- END;
- """
-
- # View for research statistics (how many documents per research)
- # DevSkim: ignore DS137138 - SQL patterns 'http://%' are for URL parsing, not insecure URLs
- research_download_stats_view = """
- CREATE OR REPLACE VIEW research_download_stats AS
- SELECT
- rh.id as research_id,
- rh.title,
- rh.query,
- rh.mode,
- rh.created_at,
- rh.status,
-
- -- Count of resources
- COUNT(DISTINCT rr.id) as total_resources,
-
- -- Count of downloaded documents
- COUNT(DISTINCT ld.id) as downloaded_count,
-
- -- Download statistics
- SUM(CASE WHEN ld.download_status = 'completed' THEN 1 ELSE 0 END) as completed_downloads,
- SUM(CASE WHEN ld.download_status = 'failed' THEN 1 ELSE 0 END) as failed_downloads,
- SUM(CASE WHEN ld.download_status = 'pending' THEN 1 ELSE 0 END) as pending_downloads,
-
- -- File type breakdown
- SUM(CASE WHEN ld.file_type = 'pdf' THEN 1 ELSE 0 END) as pdf_count,
- SUM(CASE WHEN ld.file_type = 'html' THEN 1 ELSE 0 END) as html_count,
-
- -- Size statistics
- SUM(ld.file_size) as total_size_bytes,
- AVG(ld.file_size) as avg_size_bytes,
-
- -- Domain breakdown (DevSkim: ignore DS137138 - URL pattern matching)
- COUNT(DISTINCT
- CASE
- WHEN rr.url LIKE 'http://%' THEN -- DevSkim: ignore DS137138
- SUBSTRING(rr.url FROM 'http://([^/]+)') -- DevSkim: ignore DS137138
- WHEN rr.url LIKE 'https://%' THEN
- SUBSTRING(rr.url FROM 'https://([^/]+)')
- ELSE NULL
- END
- ) as unique_domains,
-
- -- Special sources
- SUM(CASE WHEN rr.url LIKE '%arxiv.org%' THEN 1 ELSE 0 END) as arxiv_count,
- SUM(CASE WHEN rr.url LIKE '%pubmed%' OR rr.url LIKE '%ncbi.nlm.nih.gov%' THEN 1 ELSE 0 END) as pubmed_count,
- SUM(CASE WHEN ld.doi IS NOT NULL THEN 1 ELSE 0 END) as doi_count,
-
- -- User rating if exists
- rr_rating.rating as user_rating,
- rr_rating.accuracy,
- rr_rating.completeness,
- rr_rating.relevance
-
- FROM research_history rh
- LEFT JOIN research_resources rr ON rr.research_id = rh.id
- LEFT JOIN library_documents ld ON ld.resource_id = rr.id
- LEFT JOIN research_ratings rr_rating ON rr_rating.research_id = rh.id
- GROUP BY
- rh.id, rh.title, rh.query, rh.mode, rh.created_at, rh.status,
- rr_rating.rating, rr_rating.accuracy, rr_rating.completeness, rr_rating.relevance;
- """
-
- # View for domain statistics
- # DevSkim: ignore DS137138 - SQL patterns 'http://%' are for URL parsing, not insecure URLs
- domain_download_stats_view = """
- CREATE OR REPLACE VIEW domain_download_stats AS
- SELECT
- -- DevSkim: ignore DS137138 - URL pattern matching for domain extraction
- CASE
- WHEN rr.url LIKE 'http://%' THEN -- DevSkim: ignore DS137138
- SUBSTRING(rr.url FROM 'http://([^/]+)') -- DevSkim: ignore DS137138
- WHEN rr.url LIKE 'https://%' THEN
- SUBSTRING(rr.url FROM 'https://([^/]+)')
- ELSE 'unknown'
- END as domain,
-
- dc.category as domain_category,
- dc.subcategory as domain_subcategory,
-
- COUNT(DISTINCT ld.id) as download_count,
- COUNT(DISTINCT ld.research_id) as research_count,
- SUM(ld.file_size) as total_size_bytes,
- AVG(ld.file_size) as avg_size_bytes,
-
- -- File types
- SUM(CASE WHEN ld.file_type = 'pdf' THEN 1 ELSE 0 END) as pdf_count,
- SUM(CASE WHEN ld.file_type = 'html' THEN 1 ELSE 0 END) as html_count,
-
- -- Success rate
- SUM(CASE WHEN ld.download_status = 'completed' THEN 1 ELSE 0 END) * 100.0 /
- NULLIF(COUNT(ld.id), 0) as success_rate
-
- FROM library_documents ld
- INNER JOIN research_resources rr ON ld.resource_id = rr.id
- LEFT JOIN domain_classifications dc ON
- dc.domain = CASE
- WHEN rr.url LIKE 'http://%' THEN -- DevSkim: ignore DS137138
- SUBSTRING(rr.url FROM 'http://([^/]+)') -- DevSkim: ignore DS137138
- WHEN rr.url LIKE 'https://%' THEN
- SUBSTRING(rr.url FROM 'https://([^/]+)')
- ELSE NULL
- END
- GROUP BY domain, dc.category, dc.subcategory
- ORDER BY download_count DESC;
- """
-
- try:
- # Create the views
- session.execute(text(library_documents_enriched_view))
- session.execute(text(research_download_stats_view))
- session.execute(text(domain_download_stats_view))
- session.commit()
- logger.info("Library views created successfully")
- except Exception:
- session.rollback()
- logger.exception("Error creating views")
- raise
-
-
-def drop_library_views(session: Session):
- """Drop the library views if they exist."""
- try:
- session.execute(
- text("DROP VIEW IF EXISTS library_documents_enriched CASCADE;")
- )
- session.execute(
- text("DROP VIEW IF EXISTS research_download_stats CASCADE;")
- )
- session.execute(
- text("DROP VIEW IF EXISTS domain_download_stats CASCADE;")
- )
- session.commit()
- logger.info("Library views dropped successfully")
- except Exception:
- session.rollback()
- logger.exception("Error dropping views")
- raise
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 70d11495f9..4767dd3c97 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -626,11 +626,7 @@ class DownloadService:
attempt.succeeded = True
# Check if library document already exists
- existing_doc = (
- session.query(Document)
- .filter_by(resource_id=resource.id)
- .first()
- )
+ existing_doc = get_document_for_resource(session, resource)
if existing_doc:
# Update existing document
@@ -745,11 +741,7 @@ class DownloadService:
if text:
# Get the document ID we just created/updated
- pdf_doc = (
- session.query(Document)
- .filter_by(resource_id=resource.id)
- .first()
- )
+ pdf_doc = get_document_for_resource(session, resource)
pdf_document_id = pdf_doc.id if pdf_doc else None
# Save text to encrypted database
@@ -1680,12 +1672,8 @@ class DownloadService:
word_count = len(text.split())
character_count = len(text)
- # Find the Document by resource_id
- doc = (
- session.query(Document)
- .filter_by(resource_id=resource.id)
- .first()
- )
+ # Find the Document for this resource
+ doc = get_document_for_resource(session, resource)
if doc:
# Update existing document with text content
@@ -1713,12 +1701,8 @@ class DownloadService:
):
"""Record a failed text extraction attempt in the Document."""
try:
- # Find the Document by resource_id
- doc = (
- session.query(Document)
- .filter_by(resource_id=resource.id)
- .first()
- )
+ # Find the Document for this resource
+ doc = get_document_for_resource(session, resource)
if doc:
# Update document with extraction error
diff --git a/tests/database/views/__init__.py b/tests/database/views/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/tests/database/views/test_library_views.py b/tests/database/views/test_library_views.py
deleted file mode 100644
index c61df91dc6..0000000000
--- a/tests/database/views/test_library_views.py
+++ /dev/null
@@ -1,196 +0,0 @@
-"""Tests for database/views/library_views.py.
-
-Covers create_library_views and drop_library_views: SQL execution,
-commit/rollback behavior, view names, and table references.
-"""
-
-import pytest
-from unittest.mock import MagicMock, patch
-
-from local_deep_research.database.views.library_views import (
- create_library_views,
- drop_library_views,
-)
-
-
-class TestCreateLibraryViews:
- """Tests for create_library_views function."""
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_execute_called_exactly_three_times(self, mock_text):
- """create_library_views calls session.execute 3 times."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- create_library_views(session)
- assert session.execute.call_count == 3
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_commit_called_once(self, mock_text):
- """create_library_views calls commit exactly once after all executes."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- create_library_views(session)
- session.commit.assert_called_once()
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_rollback_on_execute_exception(self, mock_text):
- """On execute exception, rollback is called and exception re-raised."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- session.execute.side_effect = RuntimeError("db error")
- with pytest.raises(RuntimeError, match="db error"):
- create_library_views(session)
- session.rollback.assert_called_once()
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_commit_not_called_on_exception(self, mock_text):
- """Commit is never called when execute raises."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- session.execute.side_effect = RuntimeError("db error")
- with pytest.raises(RuntimeError):
- create_library_views(session)
- session.commit.assert_not_called()
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_sql_contains_library_documents_enriched(self, mock_text):
- """SQL contains the library_documents_enriched view name."""
- captured_sqls = []
- mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
- session = MagicMock()
- create_library_views(session)
- combined = " ".join(captured_sqls)
- assert "library_documents_enriched" in combined
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_sql_contains_research_download_stats(self, mock_text):
- """SQL contains the research_download_stats view name."""
- captured_sqls = []
- mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
- session = MagicMock()
- create_library_views(session)
- combined = " ".join(captured_sqls)
- assert "research_download_stats" in combined
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_sql_contains_domain_download_stats(self, mock_text):
- """SQL contains the domain_download_stats view name."""
- captured_sqls = []
- mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
- session = MagicMock()
- create_library_views(session)
- combined = " ".join(captured_sqls)
- assert "domain_download_stats" in combined
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_sql_references_required_tables(self, mock_text):
- """SQL references all required source tables."""
- captured_sqls = []
- mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
- session = MagicMock()
- create_library_views(session)
- combined = " ".join(captured_sqls)
- for table in [
- "library_documents",
- "research_resources",
- "research_history",
- "domain_classifications",
- ]:
- assert table in combined, f"Missing table reference: {table}"
-
-
-class TestDropLibraryViews:
- """Tests for drop_library_views function."""
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_execute_called_exactly_three_times(self, mock_text):
- """drop_library_views calls session.execute 3 times."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- drop_library_views(session)
- assert session.execute.call_count == 3
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_commit_called_once(self, mock_text):
- """drop_library_views calls commit exactly once."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- drop_library_views(session)
- session.commit.assert_called_once()
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_rollback_on_exception(self, mock_text):
- """On exception, rollback is called and exception re-raised."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- session.execute.side_effect = RuntimeError("db error")
- with pytest.raises(RuntimeError):
- drop_library_views(session)
- session.rollback.assert_called_once()
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_commit_not_called_on_exception(self, mock_text):
- """Commit is never called when execute raises."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- session.execute.side_effect = RuntimeError("db error")
- with pytest.raises(RuntimeError):
- drop_library_views(session)
- session.commit.assert_not_called()
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_drop_sql_uses_if_exists(self, mock_text):
- """Every DROP statement contains IF EXISTS."""
- captured_sqls = []
- mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
- session = MagicMock()
- drop_library_views(session)
- for sql in captured_sqls:
- assert "IF EXISTS" in sql
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_drop_sql_uses_cascade(self, mock_text):
- """Every DROP statement contains CASCADE."""
- captured_sqls = []
- mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
- session = MagicMock()
- drop_library_views(session)
- for sql in captured_sqls:
- assert "CASCADE" in sql
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_drop_targets_correct_view_names(self, mock_text):
- """DROP statements target all three expected view names."""
- captured_sqls = []
- mock_text.side_effect = lambda s: (captured_sqls.append(s), s)[1]
- session = MagicMock()
- drop_library_views(session)
- combined = " ".join(captured_sqls)
- for view in [
- "library_documents_enriched",
- "research_download_stats",
- "domain_download_stats",
- ]:
- assert view in combined
-
-
-class TestCreateThenDropSequence:
- """Test the full create-then-drop lifecycle."""
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_create_then_drop_no_error(self, mock_text):
- """Create followed by drop completes without error."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- create_library_views(session)
- drop_library_views(session)
-
- @patch("local_deep_research.database.views.library_views.text")
- def test_create_then_drop_total_calls(self, mock_text):
- """Create+drop results in 6 executes and 2 commits total."""
- mock_text.side_effect = lambda s: s
- session = MagicMock()
- create_library_views(session)
- drop_library_views(session)
- assert session.execute.call_count == 6
- assert session.commit.call_count == 2