Spaces:
Sleeping

File size: 4,219 Bytes
e7cf9be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""
Database connection and session management.
"""
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
from pathlib import Path
import logging
from typing import Generator

from .models import Base
from ..utils.config import Config


logger = logging.getLogger(__name__)


class DatabaseManager:
    """Manages database connections and sessions."""
    
    def __init__(self, config: Config = None):
        """Initialize database manager.
        
        Args:
            config: Configuration instance
        """
        self.config = config or Config()
        self.engine = None
        self.SessionLocal = None
        self._setup_database()
    
    def _setup_database(self):
        """Set up database engine and session factory."""
        db_path = self.config.get_database_path()
        
        # Ensure data directory exists
        db_path.parent.mkdir(parents=True, exist_ok=True)
        
        # Create engine with SQLite optimizations
        database_url = f"sqlite:///{db_path}"
        self.engine = create_engine(
            database_url,
            echo=False,  # Set to True for SQL debugging
            pool_pre_ping=True,
            pool_size=10,
            max_overflow=20,
            pool_timeout=30,
            pool_recycle=3600,
            connect_args={
                "check_same_thread": False,
                "timeout": 20
            }
        )
        
        # Configure SQLite for optimal performance
        self._configure_sqlite()
        
        # Create session factory
        self.SessionLocal = sessionmaker(
            autocommit=False,
            autoflush=False,
            bind=self.engine
        )
        
        logger.info(f"Database initialized at {db_path}")
    
    def _configure_sqlite(self):
        """Configure SQLite for time-series workloads."""
        with self.engine.connect() as conn:
            try:
                # Increase cache size (64MB)
                conn.execute(text("PRAGMA cache_size = -64000"))
                
                # Use WAL mode for better concurrency
                conn.execute(text("PRAGMA journal_mode = WAL"))
                
                # Optimize for bulk inserts
                conn.execute(text("PRAGMA synchronous = NORMAL"))
                conn.execute(text("PRAGMA temp_store = MEMORY"))
                
                # Enable foreign key constraints
                conn.execute(text("PRAGMA foreign_keys = ON"))
                
                conn.commit()
                logger.info("SQLite PRAGMA settings applied successfully")
            except Exception as e:
                logger.warning(f"Some SQLite PRAGMA settings may not have been applied: {e}")
                # Continue anyway as these are optimizations, not requirements
    
    def create_tables(self):
        """Create all database tables."""
        Base.metadata.create_all(bind=self.engine)
        logger.info("Database tables created")
    
    def drop_tables(self):
        """Drop all database tables."""
        Base.metadata.drop_all(bind=self.engine)
        logger.info("Database tables dropped")
    
    @contextmanager
    def get_session(self) -> Generator:
        """Get database session with automatic cleanup.
        
        Yields:
            SQLAlchemy session
        """
        session = self.SessionLocal()
        try:
            yield session
            session.commit()
        except Exception:
            session.rollback()
            raise
        finally:
            session.close()


# Global database manager instance
_db_manager = None


def get_database_manager() -> DatabaseManager:
    """Get global database manager instance."""
    global _db_manager
    if _db_manager is None:
        _db_manager = DatabaseManager()
    return _db_manager


def get_session():
    """Get database session (generator function for compatibility)."""
    db_manager = get_database_manager()
    with db_manager.get_session() as session:
        yield session


def create_tables():
    """Create all database tables."""
    db_manager = get_database_manager()
    db_manager.create_tables()