import sqlite3 from django.db import connection from apps.articles.models import Article from apps.feeds.models import Subscription from .base import SearchBackend def _fts_phrase_query(raw_query: str) -> str: """Wraps the whole user input as a single FTS5 phrase so arbitrary punctuation (hyphens, quotes, parentheses...) in a search box doesn't blow up as invalid FTS5 query syntax.""" escaped = raw_query.replace('"', '""') return f'"{escaped}"' class SQLiteFTSBackend(SearchBackend): def search(self, query: str, user, limit: int = 50): if not query.strip(): return [] feed_ids = list(Subscription.objects.filter(user=user).values_list("feed_id", flat=True)) if not feed_ids: return [] placeholders = ",".join(["%s"] * len(feed_ids)) sql = f""" SELECT a.id FROM articles_article a JOIN articles_fts f ON f.rowid = a.id WHERE articles_fts MATCH %s AND a.feed_id IN ({placeholders}) ORDER BY rank LIMIT %s """ try: with connection.cursor() as cursor: cursor.execute(sql, [_fts_phrase_query(query), *feed_ids, limit]) ordered_ids = [row[0] for row in cursor.fetchall()] except sqlite3.OperationalError: return [] if not ordered_ids: return [] articles_by_id = Article.objects.select_related("feed").in_bulk(ordered_ids) return [articles_by_id[pk] for pk in ordered_ids if pk in articles_by_id]