Spaces:
Paused

File size: 17,834 Bytes
609d292
 
 
 
 
b7f068c
 
 
609d292
 
b7f068c
 
 
 
 
 
 
 
 
 
609d292
ff28ba2
0743ddc
609d292
 
 
 
 
 
 
b7f068c
 
 
 
 
609d292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7f068c
357bfdf
0743ddc
357bfdf
0743ddc
357bfdf
 
0743ddc
357bfdf
b7f068c
609d292
b7f068c
 
 
 
 
 
 
 
609d292
 
 
 
 
b7f068c
609d292
 
357bfdf
609d292
 
8eb630b
609d292
 
8eb630b
357bfdf
8eb630b
357bfdf
609d292
 
 
 
357bfdf
0743ddc
357bfdf
 
609d292
 
0743ddc
357bfdf
 
 
 
 
 
 
 
 
 
 
609d292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7f068c
 
 
 
 
 
609d292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7f068c
609d292
 
 
 
 
 
 
 
 
 
 
 
 
b7f068c
609d292
 
 
 
 
 
 
 
 
b7f068c
 
 
 
609d292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579285c
609d292
 
 
 
 
 
 
 
 
 
b7f068c
609d292
 
 
 
 
 
 
 
 
 
 
 
579285c
609d292
 
 
 
 
 
 
 
 
 
 
357bfdf
 
 
 
 
 
0743ddc
357bfdf
 
 
0743ddc
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
0743ddc
357bfdf
0743ddc
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
0743ddc
357bfdf
 
 
 
 
 
 
609d292
 
 
 
 
 
 
d80907b
 
 
 
 
 
 
 
 
 
 
 
0743ddc
357bfdf
0743ddc
 
 
 
609d292
 
 
 
 
 
b7f068c
357bfdf
 
609d292
357bfdf
 
0743ddc
609d292
357bfdf
609d292
 
 
 
579285c
609d292
579285c
609d292
 
 
 
 
 
 
579285c
609d292
579285c
609d292
579285c
609d292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80907b
609d292
 
 
579285c
d80907b
 
 
 
 
 
609d292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579285c
609d292
 
 
 
b7f068c
609d292
 
 
 
 
 
 
 
 
 
b7f068c
609d292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357bfdf
609d292
b7f068c
357bfdf
 
 
609d292
 
 
 
 
 
 
b7f068c
 
609d292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7f068c
609d292
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
"""
YAZ Care Platform - Unified Database Management
Consolidated database engine, sessions, and connection handling
"""

from collections.abc import AsyncGenerator, Generator
from contextlib import asynccontextmanager, contextmanager
from typing import Any

import structlog
from redis.asyncio import ConnectionPool, Redis
from sqlalchemy import Engine, MetaData, create_engine, event, text
from sqlalchemy.ext.asyncio import (
    AsyncEngine,
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.pool import QueuePool, StaticPool

from .models.base import Base  # Import from base.py for consistency
from .settings import get_settings

logger = structlog.get_logger(__name__)

# Global instances
metadata = MetaData()

# Engine and session globals
_engine: Engine | None = None
_async_engine: AsyncEngine | None = None
_session_local: sessionmaker | None = None
_async_session_local: async_sessionmaker | None = None
_redis_client: Redis | None = None


def get_database_url() -> str:
    """Get database URL from settings"""
    return get_settings().database.url


def get_async_database_url() -> str:
    """Get async database URL from settings"""
    return get_settings().database.async_url


def create_sync_engine() -> Engine:
    """Create synchronous database engine with optimized settings"""
    settings = get_settings().database

    engine_kwargs = {
        "echo": settings.echo,
        "pool_pre_ping": True,
        "pool_recycle": settings.pool_recycle,
    }

    # Configure connection pool
    if settings.url.startswith("sqlite"):
        engine_kwargs.update(
            {
                "poolclass": StaticPool,
                "connect_args": {
                    "check_same_thread": False,
                    "timeout": 30,
                    "isolation_level": None,  # Autocommit mode for better concurrency
                },
            }
        )
    else:
        engine_kwargs.update(
            {
                "poolclass": QueuePool,
                "pool_size": settings.pool_size,
                "max_overflow": settings.max_overflow,
                "pool_timeout": settings.pool_timeout,
            }
        )

    engine = create_engine(settings.url, **engine_kwargs)

    # Add event listeners for healthcare-specific optimizations
    if settings.url.startswith("sqlite"):

        @event.listens_for(engine, "connect")
        def set_sqlite_pragma(dbapi_connection, connection_record):
            """Enhanced SQLite pragmas for optimal healthcare performance"""
            cursor = dbapi_connection.cursor()

            # Performance optimizations (low-resource friendly)
            cursor.execute("PRAGMA journal_mode=WAL")
            cursor.execute("PRAGMA synchronous=NORMAL")
            cursor.execute("PRAGMA cache_size=5000")  # 5K pages (~20MB)
            cursor.execute("PRAGMA temp_store=MEMORY")
            cursor.execute("PRAGMA mmap_size=134217728")  # 128MB mmap (reduced)
            cursor.execute("PRAGMA page_size=4096")  # Optimal page size

            # Data integrity for healthcare
            cursor.execute("PRAGMA foreign_keys=ON")
            cursor.execute("PRAGMA case_sensitive_like=ON")
            cursor.execute("PRAGMA secure_delete=ON")  # HIPAA compliance

            # Query optimization
            cursor.execute("PRAGMA optimize")

            cursor.close()

    else:
        # PostgreSQL connection optimizations
        @event.listens_for(engine, "connect")
        def set_postgres_settings(dbapi_connection, connection_record):
            """Optimize PostgreSQL connection for healthcare workloads"""
            with dbapi_connection.cursor() as cursor:
                # Connection-level optimizations
                cursor.execute("SET statement_timeout = '300s'")
                cursor.execute("SET lock_timeout = '30s'")
                cursor.execute("SET work_mem = '16MB'")
                cursor.execute("SET shared_preload_libraries = 'pg_stat_statements'")

    return engine


def create_async_engine_instance() -> AsyncEngine:
    """Create asynchronous database engine"""
    settings = get_settings().database

    engine_kwargs = {
        "echo": settings.echo,
        "pool_pre_ping": True,
        "pool_recycle": settings.pool_recycle,
    }

    # Configure for async
    if not settings.url.startswith("sqlite"):
        engine_kwargs.update(
            {
                "pool_size": settings.pool_size,
                "max_overflow": settings.max_overflow,
            }
        )

    return create_async_engine(get_async_database_url(), **engine_kwargs)


def get_engine() -> Engine:
    """Get or create synchronous database engine"""
    global _engine
    if _engine is None:
        _engine = create_sync_engine()
        logger.info("Synchronous database engine created")
    return _engine


def get_async_engine() -> AsyncEngine:
    """Get or create asynchronous database engine"""
    global _async_engine
    if _async_engine is None:
        _async_engine = create_async_engine_instance()
        logger.info("Asynchronous database engine created")
    return _async_engine


def get_session_local() -> sessionmaker:
    """Get or create session factory"""
    global _session_local
    if _session_local is None:
        _session_local = sessionmaker(autocommit=False, autoflush=False, bind=get_engine())
        logger.info("Session factory created")
    return _session_local


def get_async_session_local() -> async_sessionmaker:
    """Get or create async session factory"""
    global _async_session_local
    if _async_session_local is None:
        _async_session_local = async_sessionmaker(
            bind=get_async_engine(),
            class_=AsyncSession,
            autocommit=False,
            autoflush=False,
            expire_on_commit=False,
        )
        logger.info("Async session factory created")
    return _async_session_local


# Session factories for dependency injection
SessionLocal = get_session_local
AsyncSessionLocal = get_async_session_local

# Engine exports for backwards compatibility
engine = get_engine
async_engine = get_async_engine


def get_db() -> Generator[Session, None, None]:
    """Database session dependency for FastAPI"""
    session = get_session_local()()
    try:
        yield session
        session.commit()
    except Exception:
        session.rollback()
        raise
    finally:
        session.close()


async def get_async_db() -> AsyncGenerator[AsyncSession, None]:
    """Async database session dependency for FastAPI"""
    async_session = get_async_session_local()
    async with async_session() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise


@contextmanager
def get_db_session():
    """Context manager for database sessions"""
    session = get_session_local()()
    try:
        yield session
        session.commit()
    except Exception:
        session.rollback()
        raise
    finally:
        session.close()


@asynccontextmanager
async def get_async_db_session():
    """Async context manager for database sessions"""
    async_session = get_async_session_local()
    async with async_session() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise


def get_db_context():
    """Alternative name for get_db_session"""
    return get_db_session()


def get_async_db_context():
    """Alternative name for get_async_db_session"""
    return get_async_db_session()


def test_connection() -> bool:
    """Test database connection"""
    try:
        engine = get_engine()
        with engine.connect() as connection:
            connection.execute(text("SELECT 1"))
        logger.info("Database connection test successful")
        return True
    except Exception as e:
        logger.error("Database connection test failed", error=str(e))
        return False


async def test_async_connection() -> bool:
    """Test async database connection"""
    try:
        engine = get_async_engine()
        async with engine.connect() as connection:
            await connection.execute(text("SELECT 1"))
        logger.info("Async database connection test successful")
        return True
    except Exception as e:
        logger.error("Async database connection test failed", error=str(e))
        return False


async def get_redis() -> Redis:
    """Get Redis client for caching and session management"""
    global _redis_client

    settings = get_settings().redis
    if not settings.enabled:
        logger.warning("Redis is disabled in configuration")
        return None  # type: ignore[name-defined, index, return-value, var-annotated]

    if _redis_client is None:
        try:
            # Create connection pool
            pool = ConnectionPool.from_url(
                settings.url,
                max_connections=settings.max_connections,
                socket_timeout=settings.socket_timeout,
                socket_connect_timeout=settings.socket_connect_timeout,
                retry_on_timeout=settings.retry_on_timeout,
                decode_responses=True,
            )

            _redis_client = Redis(connection_pool=pool)

            # Test connection
            await _redis_client.ping()
            logger.info("Redis client created and connected")

        except Exception as e:
            logger.error("Failed to create Redis client", error=str(e))
            _redis_client = None

    return _redis_client  # type: ignore[name-defined, index, return-value, var-annotated]


async def close_redis():
    """Close Redis connection"""
    global _redis_client
    if _redis_client:
        await _redis_client.close()
        _redis_client = None
        logger.info("Redis client closed")


async def cache_get(key: str) -> Any | None:
    """Get value from Redis cache with error handling"""
    try:
        redis_client = await get_redis()
        if not redis_client:
            return None

        value = await redis_client.get(key)
        if value:
            import json

            return json.loads(value)
        return None
    except Exception as e:
        logger.warning(f"Cache get failed for key {key}", error=str(e))
        return None


async def cache_set(key: str, value: Any, ttl: int = 3600) -> bool:
    """Set value in Redis cache with error handling"""
    try:
        redis_client = await get_redis()
        if not redis_client:
            return False

        import json

        await redis_client.setex(key, ttl, json.dumps(value, default=str))
        return True
    except Exception as e:
        logger.warning(f"Cache set failed for key {key}", error=str(e))
        return False


async def cache_delete(key: str) -> bool:
    """Delete key from Redis cache"""
    try:
        redis_client = await get_redis()
        if not redis_client:
            return False

        await redis_client.delete(key)
        return True
    except Exception as e:
        logger.warning(f"Cache delete failed for key {key}", error=str(e))
        return False


def init_database() -> None:
    """Initialize database and create tables"""
    try:
        engine = get_engine()

        # Import all models to ensure they're registered

        # Schema bootstrap — SQLite (dev) only.
        # In production (PostgreSQL) schema is managed by Alembic migrations.
        # Calling create_all on PostgreSQL bypasses migration history and
        # risks silent schema drift.
        if str(engine.url).startswith("sqlite"):
            Base.metadata.create_all(bind=engine)
            logger.info("Database initialized and tables created")
        else:
            logger.info(
                "PostgreSQL detected — skipping create_all; "
                "run 'alembic upgrade head' to apply pending migrations."
            )

        # Log connection pool status
        if hasattr(engine.pool, "size"):
            logger.info(
                f"Connection pool initialized - Size: {engine.pool.size()}, Checked out: {engine.pool.checkedout()}"
            )  # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]

    except Exception as e:
        logger.error("Database initialization failed", error=str(e))
        raise


async def get_database_health() -> dict[str, Any]:
    """Get comprehensive database and cache health status"""
    health = {"database": False, "redis": False, "details": {}, "performance": {}}

    # Test database connection with timing
    import time

    try:
        start_time = time.time()
        engine = get_engine()
        with engine.connect() as connection:
            result = connection.execute(text("SELECT 1")).scalar()
            health["database"] = result == 1
            health["details"]["database"] = "Connected"  # type: ignore[name-defined, index, return-value, var-annotated]
    except Exception as e:
        health["details"]["database"] = f"Error: {str(e)}"  # type: ignore[name-defined, index, return-value, var-annotated]

    # Test Redis connection
    try:
        redis_client = await get_redis()
        if redis_client:
            await redis_client.ping()
            health["redis"] = True
            health["details"]["redis"] = "Connected"  # type: ignore[name-defined, index, return-value, var-annotated]
        else:
            health["details"]["redis"] = "Disabled or not configured"  # type: ignore[name-defined, index, return-value, var-annotated]
    except Exception as e:
        health["details"]["redis"] = f"Error: {str(e)}"  # type: ignore[name-defined, index, return-value, var-annotated]

    return health


class DatabaseManager:
    """Healthcare-specific database management utilities"""

    def __init__(self):
        self.engine = None
        self.SessionLocal = None

    def initialize(self):
        """Initialize database manager"""
        self.engine = get_engine()
        self.SessionLocal = get_session_local()
        logger.info("Database manager initialized")

    def create_tables(self):
        """Create all database tables (SQLite/dev only; use Alembic in production)"""
        if not self.engine:
            self.initialize()

        if str(self.engine.url).startswith("sqlite"):  # type: ignore[union-attr]
            Base.metadata.create_all(bind=self.engine)
            logger.info("Database tables created")
        else:
            logger.warning(
                "create_tables() called on PostgreSQL — use 'alembic upgrade head' instead."
            )

    def check_connection(self) -> bool:
        """Check database connectivity"""
        return test_connection()

    async def check_redis_connection(self) -> bool:
        """Check Redis connectivity"""
        try:
            redis_client = await get_redis()
            if redis_client:
                await redis_client.ping()
                return True
            return False
        except Exception:
            return False

    def get_session(self) -> Session:
        """Get database session"""
        if not self.SessionLocal:
            self.initialize()
        return self.SessionLocal()  # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]

    def get_active_patients_count(self) -> int:
        """Get count of active patients"""
        try:
            with get_db_session():
                # This would need to be implemented based on your actual Patient model
                # For now, return 0 as placeholder
                return 0
        except Exception as e:
            logger.error("Failed to get active patients count", error=str(e))
            return 0

    def get_pending_surgeries_count(self) -> int:
        """Get count of pending surgeries"""
        try:
            with get_db_session():
                # This would need to be implemented based on your actual models
                # For now, return 0 as placeholder
                return 0
        except Exception as e:
            logger.error("Failed to get pending surgeries count", error=str(e))
            return 0


# Global database manager instance
db_manager = DatabaseManager()


# Cleanup functions
async def close_database_connections():
    """Close all database connections"""
    global _engine, _async_engine, _session_local, _async_session_local

    # Close Redis
    await close_redis()

    # Close async engine
    if _async_engine:
        await _async_engine.dispose()
        _async_engine = None

    # Close sync engine
    if _engine:
        _engine.dispose()
        _engine = None

    # Reset session factories
    _session_local = None
    _async_session_local = None

    logger.info("All database connections closed")


# Initialize database on module import
try:
    # Only initialize if not in testing - disabled for migration
    import os

    # Temporarily disabled for Alembic migration setup
    # if os.getenv("TESTING") != "1":
    #     init_database()
except Exception as e:
    logger.warning("Database initialization deferred", error=str(e))


__all__ = [
    "Base",
    "metadata",
    "engine",
    "async_engine",
    "get_engine",
    "get_async_engine",
    "get_session_local",
    "get_async_session_local",
    "SessionLocal",
    "AsyncSessionLocal",
    "get_db",
    "get_async_db",
    "get_db_session",
    "get_async_db_session",
    "get_db_context",
    "get_async_db_context",
    "get_redis",
    "test_connection",
    "test_async_connection",
    "init_database",
    "get_database_health",
    "DatabaseManager",
    "db_manager",
    "close_database_connections",
]