Spaces:
Paused

File size: 14,337 Bytes
357bfdf
 
 
 
 
 
 
579285c
357bfdf
 
 
 
 
 
 
 
 
 
 
2e7af6d
357bfdf
 
 
 
8eb630b
 
 
2e7af6d
8eb630b
 
 
 
579285c
357bfdf
2e7af6d
357bfdf
 
 
 
 
2e7af6d
357bfdf
2a99443
372384b
 
 
 
 
357bfdf
 
 
 
 
2e7af6d
357bfdf
 
 
 
 
2e7af6d
357bfdf
372384b
ff28ba2
2e7af6d
372384b
 
 
2e7af6d
372384b
 
 
2e7af6d
 
 
 
 
 
 
 
 
 
372384b
2e7af6d
372384b
 
 
2e7af6d
372384b
2e7af6d
d80907b
 
 
2e7af6d
d80907b
2e7af6d
d80907b
 
 
 
357bfdf
 
 
 
2e7af6d
357bfdf
 
 
 
2e7af6d
357bfdf
 
 
2e7af6d
357bfdf
 
 
 
2e7af6d
357bfdf
 
 
 
2e7af6d
357bfdf
 
 
2e7af6d
 
 
 
 
357bfdf
2e7af6d
357bfdf
 
2e7af6d
 
 
 
 
357bfdf
 
 
2e7af6d
357bfdf
 
 
 
 
 
 
2e7af6d
357bfdf
 
 
2e7af6d
357bfdf
2e7af6d
357bfdf
2e7af6d
357bfdf
2e7af6d
 
357bfdf
 
 
 
 
2e7af6d
357bfdf
579285c
357bfdf
2e7af6d
 
 
357bfdf
 
 
 
 
 
 
 
 
2e7af6d
 
 
 
357bfdf
2e7af6d
 
 
357bfdf
 
 
 
 
 
 
 
 
2e7af6d
 
 
 
357bfdf
2e7af6d
 
 
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
 
 
 
357bfdf
 
 
2e7af6d
357bfdf
 
 
2e7af6d
357bfdf
 
 
 
2e7af6d
357bfdf
579285c
357bfdf
2e7af6d
 
 
 
357bfdf
 
2e7af6d
 
 
357bfdf
 
 
 
 
 
2e7af6d
 
 
357bfdf
 
2e7af6d
357bfdf
2e7af6d
357bfdf
 
 
2e7af6d
357bfdf
 
 
 
 
2e7af6d
357bfdf
 
2e7af6d
357bfdf
 
 
2e7af6d
357bfdf
2e7af6d
357bfdf
 
2e7af6d
 
357bfdf
 
 
 
2e7af6d
357bfdf
 
 
2e7af6d
357bfdf
2e7af6d
 
 
 
357bfdf
2e7af6d
357bfdf
 
2e7af6d
357bfdf
 
2e7af6d
 
 
 
 
 
 
 
 
 
 
357bfdf
2e7af6d
357bfdf
579285c
2e7af6d
579285c
2e7af6d
357bfdf
 
 
 
 
2e7af6d
357bfdf
 
 
 
 
2e7af6d
357bfdf
2e7af6d
357bfdf
 
2e7af6d
 
357bfdf
 
 
 
 
 
2e7af6d
357bfdf
 
 
2e7af6d
8eb630b
357bfdf
8eb630b
 
2e7af6d
8eb630b
2e7af6d
8eb630b
 
 
357bfdf
 
2e7af6d
579285c
357bfdf
 
2e7af6d
357bfdf
 
 
 
 
 
 
 
2e7af6d
357bfdf
2e7af6d
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
"""
YAZ Care Platform - Database Manager
PostgreSQL production database with multi-tenant support and HIPAA compliance
"""

import os
import asyncio
import structlog
from typing import Dict, Any, Optional, List
from datetime import datetime
from pathlib import Path

try:
    import sqlalchemy as sa
    from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
    from sqlalchemy.orm import declarative_base, sessionmaker
    from sqlalchemy.sql import text
    from alembic import command
    from alembic.config import Config

    ASYNC_DB_AVAILABLE = True
except ImportError:
    ASYNC_DB_AVAILABLE = False

# asyncpg is optional - only needed for PostgreSQL
try:
    import asyncpg

    ASYNCPG_AVAILABLE = True
except ImportError:
    ASYNCPG_AVAILABLE = False

logger = structlog.get_logger(__name__)


class DatabaseManager:
    """
    Production database manager with multi-tenant support
    Features: Connection pooling, RLS, HIPAA compliance, automated migrations
    """

    def __init__(self):
        db_url = os.getenv("DATABASE_URL", "sqlite:///./data/databases/yaz_care.db")
        # Convert sqlite:// to sqlite+aiosqlite:// for async support
        if db_url.startswith("sqlite://"):
            self.database_url = db_url.replace("sqlite://", "sqlite+aiosqlite://")
        else:
            self.database_url = db_url
        self.is_postgresql = self.database_url.startswith("postgresql")
        self.engine = None
        self.async_session_maker = None
        self.tenant_isolation = os.getenv("TENANT_ISOLATION_ENABLED", "false").lower() == "true"
        self.rls_enabled = os.getenv("RLS_ENABLED", "false").lower() == "true"

    async def initialize(self):
        """Initialize database connection and setup"""
        if not ASYNC_DB_AVAILABLE:
            logger.warning("Async database dependencies not available")
            return False

        try:
            # Import optimization settings
            from core.database.query_optimizer import get_optimal_pool_settings

            # Get environment-specific pool settings
            env = os.getenv("ENVIRONMENT", "development")
            pool_settings = get_optimal_pool_settings(env)

            # Create async engine with optimized production settings
            engine_kwargs = {
                "pool_size": int(os.getenv("DB_POOL_SIZE", str(pool_settings["pool_size"]))),
                "max_overflow": int(
                    os.getenv("DB_MAX_OVERFLOW", str(pool_settings["max_overflow"]))
                ),
                "pool_timeout": int(
                    os.getenv("DB_POOL_TIMEOUT", str(pool_settings["pool_timeout"]))
                ),
                "pool_recycle": int(
                    os.getenv("DB_POOL_RECYCLE", str(pool_settings["pool_recycle"]))
                ),
                "echo": os.getenv("DEBUG", "false").lower() == "true",
            }

            # Add pool_pre_ping for PostgreSQL (not supported by SQLite)
            if self.is_postgresql and pool_settings.get("pool_pre_ping"):
                engine_kwargs["pool_pre_ping"] = True

            self.engine = create_async_engine(self.database_url, **engine_kwargs)

            # Register engine for pool telemetry (Prometheus db_pool_* metrics)
            try:
                from monitoring.prometheus_metrics import register_db_engine

                # asyncpg engine exposes pool via sync_engine
                _sync_engine = getattr(self.engine, "sync_engine", self.engine)
                register_db_engine(_sync_engine, name="primary")
            except Exception:
                pass  # Non-fatal: metrics simply won't show pool stats

            # Create session maker
            self.async_session_maker = async_sessionmaker(
                self.engine, class_=AsyncSession, expire_on_commit=False
            )

            # Test connection
            await self.health_check()
            logger.info("✅ Database initialized successfully")
            return True

        except Exception as e:
            logger.error(f"❌ Database initialization failed: {e}")
            return False

    async def health_check(self) -> Dict[str, Any]:
        """Comprehensive database health check"""
        if not self.engine:
            return {"status": "error", "message": "Database not initialized"}

        try:
            async with self.engine.connect() as conn:
                # Basic connectivity
                await conn.execute(text("SELECT 1"))

                # Check PostgreSQL specific features
                if self.is_postgresql:
                    # Check RLS support
                    rls_result = await conn.execute(
                        text(
                            "SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public'"
                        )
                    )
                    table_count = rls_result.scalar()

                    # Check for tenant isolation table
                    if self.tenant_isolation:
                        tenant_check = await conn.execute(
                            text(
                                "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'tenants')"
                            )
                        )
                        tenant_table_exists = tenant_check.scalar()
                    else:
                        tenant_table_exists = None

                    return {
                        "status": "healthy",
                        "database_type": "postgresql",
                        "table_count": table_count,
                        "rls_enabled": self.rls_enabled,
                        "tenant_isolation": self.tenant_isolation,
                        "tenant_table_exists": tenant_table_exists,
                        "timestamp": datetime.now().isoformat(),
                    }
                else:
                    return {
                        "status": "healthy",
                        "database_type": "sqlite",
                        "timestamp": datetime.now().isoformat(),
                    }

        except Exception as e:
            return {"status": "error", "message": str(e), "timestamp": datetime.now().isoformat()}

    async def setup_multi_tenant_schema(self):
        """Setup multi-tenant schema with Row Level Security"""
        if not self.is_postgresql or not self.tenant_isolation:
            logger.info("Multi-tenant setup skipped (not PostgreSQL or disabled)")
            return True

        try:
            async with self.engine.connect() as conn:  # type: ignore[union-attr]
                # Create tenants table
                await conn.execute(
                    text(
                        """
                    CREATE TABLE IF NOT EXISTS tenants (
                        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                        name VARCHAR(255) NOT NULL UNIQUE,
                        subdomain VARCHAR(100) UNIQUE,
                        settings JSONB DEFAULT '{}',
                        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
                        updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
                        active BOOLEAN DEFAULT TRUE
                    )
                """
                    )
                )

                # Create tenant context function
                await conn.execute(
                    text(
                        """
                    CREATE OR REPLACE FUNCTION get_current_tenant_id() 
                    RETURNS UUID AS $$
                    BEGIN
                        RETURN current_setting('app.tenant_id', true)::UUID;
                    EXCEPTION 
                        WHEN others THEN
                            RETURN NULL;
                    END;
                    $$ LANGUAGE plpgsql STABLE;
                """
                    )
                )

                # Create audit log table for HIPAA compliance
                await conn.execute(
                    text(
                        """
                    CREATE TABLE IF NOT EXISTS audit_logs (
                        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                        tenant_id UUID REFERENCES tenants(id),
                        user_id UUID,
                        action VARCHAR(100) NOT NULL,
                        resource_type VARCHAR(100),
                        resource_id VARCHAR(255),
                        old_values JSONB,
                        new_values JSONB,
                        ip_address INET,
                        user_agent TEXT,
                        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
                    )
                """
                    )
                )

                await conn.commit()
                logger.info("✅ Multi-tenant schema setup complete")
                return True

        except Exception as e:
            logger.error(f"❌ Multi-tenant schema setup failed: {e}")
            return False

    async def create_default_tenant(self):
        """Create default tenant for initial setup"""
        if not self.tenant_isolation:
            return True

        try:
            async with self.async_session_maker() as session:  # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
                # Check if default tenant exists
                result = await session.execute(
                    text("SELECT id FROM tenants WHERE name = 'Default Healthcare Organization'")
                )

                if not result.scalar():
                    # Create default tenant
                    await session.execute(
                        text(
                            """
                        INSERT INTO tenants (name, subdomain, settings)
                        VALUES (
                            'Default Healthcare Organization',
                            'default',
                            '{"features": ["all"], "max_users": 1000}'
                        )
                    """
                        )
                    )
                    await session.commit()
                    logger.info("✅ Default tenant created")

                return True

        except Exception as e:
            logger.error(f"❌ Default tenant creation failed: {e}")
            return False

    async def run_migrations(self) -> Dict[str, Any]:
        """Run database migrations"""
        try:
            # Setup Alembic configuration
            alembic_cfg = Config("alembic.ini")

            # Run migrations
            command.upgrade(alembic_cfg, "head")

            return {
                "status": "success",
                "message": "Migrations completed successfully",
                "timestamp": datetime.now().isoformat(),
            }

        except Exception as e:
            logger.error(f"Migration failed: {e}")
            return {"status": "error", "message": str(e), "timestamp": datetime.now().isoformat()}

    async def backup_database(self) -> Dict[str, Any]:
        """Create database backup"""
        if not self.is_postgresql:
            return {"status": "skipped", "message": "Backup only supported for PostgreSQL"}

        try:
            # Extract connection details
            import urllib.parse as urlparse

            parsed = urlparse.urlparse(self.database_url)

            backup_path = (
                Path("./backups") / f"yazcare_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.sql"
            )
            backup_path.parent.mkdir(exist_ok=True)

            # Use pg_dump for backup
            import subprocess

            cmd = [
                "pg_dump",
                "-h",
                parsed.hostname,
                "-p",
                str(parsed.port),
                "-U",
                parsed.username,
                "-d",
                parsed.path[1:],  # Remove leading slash
                "-f",
                str(backup_path),
                "--verbose",
            ]

            env = os.environ.copy()
            env["PGPASSWORD"] = parsed.password  # type: ignore[arg-type, assignment]

            result = subprocess.run(cmd, env=env, capture_output=True, text=True)  # type: ignore[arg-type, assignment]

            if result.returncode == 0:
                return {
                    "status": "success",
                    "backup_path": str(backup_path),
                    "size_mb": backup_path.stat().st_size / (1024 * 1024),
                    "timestamp": datetime.now().isoformat(),
                }
            else:
                return {
                    "status": "error",
                    "message": result.stderr,
                    "timestamp": datetime.now().isoformat(),
                }

        except Exception as e:
            logger.error(f"Backup failed: {e}")
            return {"status": "error", "message": str(e), "timestamp": datetime.now().isoformat()}

    async def close(self):
        """Close database connections"""
        if self.engine:
            await self.engine.dispose()
            logger.info("Database connections closed")


# Global database manager instance
db_manager = DatabaseManager()


# Convenience functions - FastAPI dependency injection compatible
async def get_db_session():
    """
    Get database session as async generator for FastAPI Depends().

    Usage: session: AsyncSession = Depends(get_db_session)

    Note: Do NOT use @asynccontextmanager decorator - FastAPI handles
    the context management automatically for async generators.
    """
    if not db_manager.async_session_maker:
        await db_manager.initialize()

    async with db_manager.async_session_maker() as session:  # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
        yield session


async def init_database():
    """Initialize database system"""
    success = await db_manager.initialize()
    if success and db_manager.is_postgresql:
        await db_manager.setup_multi_tenant_schema()
        await db_manager.create_default_tenant()
    return success


# Export main components
__all__ = ["DatabaseManager", "db_manager", "get_db_session", "init_database"]