search.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. SQLite FTS5 search backend - search and flush operations.
  3. This module provides the search interface for the SQLite FTS backend.
  4. Environment variables:
  5. SQLITEFTS_DB: Database filename (default: search.sqlite3)
  6. FTS_SEPARATE_DATABASE: Use separate database file (default: true)
  7. FTS_TOKENIZERS: FTS5 tokenizer config (default: porter unicode61 remove_diacritics 2)
  8. """
  9. import os
  10. import sqlite3
  11. from pathlib import Path
  12. from typing import List, Iterable
  13. from django.conf import settings
  14. # Config with old var names for backwards compatibility
  15. SQLITEFTS_DB = os.environ.get('SQLITEFTS_DB', 'search.sqlite3').strip()
  16. FTS_SEPARATE_DATABASE = os.environ.get('FTS_SEPARATE_DATABASE', 'true').lower() in ('true', '1', 'yes')
  17. FTS_TOKENIZERS = os.environ.get('FTS_TOKENIZERS', 'porter unicode61 remove_diacritics 2').strip()
  18. def get_db_path() -> Path:
  19. """Get path to the search index database."""
  20. return Path(settings.DATA_DIR) / SQLITEFTS_DB
  21. def search(query: str) -> List[str]:
  22. """Search for snapshots matching the query."""
  23. db_path = get_db_path()
  24. if not db_path.exists():
  25. return []
  26. conn = sqlite3.connect(str(db_path))
  27. try:
  28. cursor = conn.execute(
  29. 'SELECT DISTINCT snapshot_id FROM search_index WHERE search_index MATCH ?',
  30. (query,)
  31. )
  32. return [row[0] for row in cursor.fetchall()]
  33. except sqlite3.OperationalError:
  34. # Table doesn't exist yet
  35. return []
  36. finally:
  37. conn.close()
  38. def flush(snapshot_ids: Iterable[str]) -> None:
  39. """Remove snapshots from the index."""
  40. db_path = get_db_path()
  41. if not db_path.exists():
  42. return
  43. conn = sqlite3.connect(str(db_path))
  44. try:
  45. for snapshot_id in snapshot_ids:
  46. conn.execute('DELETE FROM search_index WHERE snapshot_id = ?', (snapshot_id,))
  47. conn.commit()
  48. except sqlite3.OperationalError:
  49. pass # Table doesn't exist
  50. finally:
  51. conn.close()