Coverage for src / local_deep_research / library / download_management / database_init.py: 89%

24 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-02-25 01:07 +0000

1""" 

2Database Initialization for Download Management 

3 

4Creates the necessary database tables for tracking download status and retry logic. 

5""" 

6 

7from sqlalchemy import create_engine, inspect 

8from loguru import logger 

9 

10from .models import Base 

11 

12 

13def init_database(): 

14 """Initialize the database with required tables""" 

15 

16 # Create engine - use same path as research_library module 

17 engine = create_engine("sqlite:///data/research_library.db") 

18 

19 try: 

20 # Create tables 

21 Base.metadata.create_all(engine) 

22 logger.info( 

23 "Download management database tables initialized successfully" 

24 ) 

25 finally: 

26 # Always dispose engine to prevent file descriptor leaks 

27 engine.dispose() 

28 

29 # Return None since engine is disposed - callers should create their own 

30 # engine/session if they need to interact with the database 

31 return None 

32 

33 

34def verify_table_exists(): 

35 """Verify that the required tables exist""" 

36 

37 engine = create_engine("sqlite:///data/research_library.db") 

38 

39 try: 

40 # Check if table exists using SQLAlchemy's inspect function 

41 inspector = inspect(engine) 

42 table_names = inspector.get_table_names() 

43 

44 if "resource_download_status" in table_names: 

45 logger.info("✓ resource_download_status table exists") 

46 return True 

47 else: 

48 logger.warning("✗ resource_download_status table missing") 

49 return False 

50 finally: 

51 # Always dispose engine to prevent file descriptor leaks 

52 engine.dispose() 

53 

54 

55if __name__ == "__main__": 55 ↛ 57line 55 didn't jump to line 57 because the condition on line 55 was never true

56 # Initialize database when run directly 

57 init_database() 

58 verify_table_exists()