""" YAZ Care Platform - PostgreSQL Setup Script Production database initialization with multi-tenant support """ import asyncio import os import sys import logging from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) try: import asyncpg import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT except ImportError: print("❌ PostgreSQL dependencies not installed") print("Run: pip install asyncpg psycopg2-binary") sys.exit(1) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def create_database(): """Create PostgreSQL database and user""" # Database configuration config = { 'host': os.getenv('POSTGRES_HOST', 'localhost'), 'port': int(os.getenv('POSTGRES_PORT', '5432')), 'user': os.getenv('POSTGRES_ADMIN_USER', 'postgres'), 'password': os.getenv('POSTGRES_ADMIN_PASSWORD', ''), 'target_db': os.getenv('POSTGRES_DB', 'yazcare_prod'), 'target_user': os.getenv('POSTGRES_USER', 'yazcare_user'), 'target_password': os.getenv('POSTGRES_PASSWORD', 'yazcare_secure_2025') } try: # Connect as admin user logger.info("🔗 Connecting to PostgreSQL as admin...") conn = psycopg2.connect( host=config['host'], port=config['port'], user=config['user'], password=config['password'], database='postgres' ) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() # Create user if not exists logger.info(f"👤 Creating user: {config['target_user']}") cursor.execute(f""" DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{config['target_user']}') THEN CREATE USER {config['target_user']} WITH PASSWORD '{config['target_password']}'; END IF; END $$; """) # Create database if not exists logger.info(f"🗄️ Creating database: {config['target_db']}") cursor.execute(f""" SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{config['target_db']}' """) if not cursor.fetchone(): cursor.execute(f""" CREATE DATABASE {config['target_db']} OWNER {config['target_user']} ENCODING 'UTF8' """) # Grant permissions logger.info("🔐 Granting permissions...") cursor.execute(f"GRANT ALL PRIVILEGES ON DATABASE {config['target_db']} TO {config['target_user']}") cursor.execute(f"ALTER USER {config['target_user']} CREATEDB") cursor.close() conn.close() # Connect to target database and setup extensions logger.info("📦 Setting up database extensions...") conn = psycopg2.connect( host=config['host'], port=config['port'], user=config['target_user'], password=config['target_password'], database=config['target_db'] ) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() # Create extensions extensions = [ 'uuid-ossp', # UUID generation 'pgcrypto', # Cryptographic functions 'pg_stat_statements' # Query statistics ] for ext in extensions: try: cursor.execute(f"CREATE EXTENSION IF NOT EXISTS \"{ext}\"") logger.info(f"✅ Extension created: {ext}") except Exception as e: logger.warning(f"⚠️ Extension {ext} not available: {e}") cursor.close() conn.close() logger.info("✅ PostgreSQL setup completed successfully!") return True except Exception as e: logger.error(f"❌ PostgreSQL setup failed: {e}") return False async def setup_row_level_security(): """Setup Row Level Security for multi-tenant isolation""" config = { 'host': os.getenv('POSTGRES_HOST', 'localhost'), 'port': int(os.getenv('POSTGRES_PORT', '5432')), 'user': os.getenv('POSTGRES_USER', 'yazcare_user'), 'password': os.getenv('POSTGRES_PASSWORD', 'yazcare_secure_2025'), 'database': os.getenv('POSTGRES_DB', 'yazcare_prod') } try: conn = psycopg2.connect(**config) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() logger.info("🔒 Setting up Row Level Security...") # Create tenant-aware tables with RLS tables_sql = """ -- Tenants table 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 ); -- Users table with tenant isolation CREATE TABLE IF NOT EXISTS users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, email VARCHAR(255) NOT NULL, password_hash VARCHAR(255) NOT NULL, first_name VARCHAR(100), last_name VARCHAR(100), role VARCHAR(50) DEFAULT 'user', active BOOLEAN DEFAULT TRUE, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), UNIQUE(tenant_id, email) ); -- Medical records with tenant isolation CREATE TABLE IF NOT EXISTS medical_records ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, patient_id UUID NOT NULL, record_type VARCHAR(100) NOT NULL, content JSONB NOT NULL, created_by UUID REFERENCES users(id), created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Audit logs for HIPAA compliance CREATE TABLE IF NOT EXISTS audit_logs ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID REFERENCES tenants(id), user_id UUID REFERENCES users(id), 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, session_id VARCHAR(255), created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); """ cursor.execute(tables_sql) # Enable RLS on tenant-isolated tables rls_tables = ['users', 'medical_records', 'audit_logs'] for table in rls_tables: cursor.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY") # Create RLS policies cursor.execute(f""" CREATE POLICY tenant_isolation ON {table} FOR ALL TO PUBLIC USING (tenant_id = current_setting('app.tenant_id', true)::UUID) """) logger.info(f"✅ RLS enabled for table: {table}") # Create helper functions cursor.execute(""" 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 SECURITY DEFINER; CREATE OR REPLACE FUNCTION set_tenant_context(tenant_uuid UUID) RETURNS VOID AS $$ BEGIN PERFORM set_config('app.tenant_id', tenant_uuid::TEXT, false); END; $$ LANGUAGE plpgsql SECURITY DEFINER; """) # Insert default tenant cursor.execute(""" INSERT INTO tenants (name, subdomain, settings) VALUES ( 'Default Healthcare Organization', 'default', '{"features": ["all"], "max_users": 1000, "storage_gb": 100}' ) ON CONFLICT (name) DO NOTHING """) cursor.close() conn.close() logger.info("✅ Row Level Security setup completed!") return True except Exception as e: logger.error(f"❌ RLS setup failed: {e}") return False async def create_indexes(): """Create performance indexes""" config = { 'host': os.getenv('POSTGRES_HOST', 'localhost'), 'port': int(os.getenv('POSTGRES_PORT', '5432')), 'user': os.getenv('POSTGRES_USER', 'yazcare_user'), 'password': os.getenv('POSTGRES_PASSWORD', 'yazcare_secure_2025'), 'database': os.getenv('POSTGRES_DB', 'yazcare_prod') } try: conn = psycopg2.connect(**config) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() logger.info("📊 Creating performance indexes...") indexes = [ "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_tenant_email ON users(tenant_id, email)", "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_medical_records_tenant_patient ON medical_records(tenant_id, patient_id)", "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_audit_logs_tenant_created ON audit_logs(tenant_id, created_at DESC)", "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_audit_logs_user_action ON audit_logs(user_id, action)", "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_medical_records_type_created ON medical_records(record_type, created_at DESC)" ] for index_sql in indexes: try: cursor.execute(index_sql) logger.info("✅ Index created successfully") except Exception as e: logger.warning(f"⚠️ Index creation failed: {e}") cursor.close() conn.close() logger.info("✅ Performance indexes created!") return True except Exception as e: logger.error(f"❌ Index creation failed: {e}") return False async def main(): """Main setup function""" logger.info("🏥 YAZ Care Platform - PostgreSQL Setup") logger.info("=" * 50) # Step 1: Create database and user if await create_database(): logger.info("✅ Database creation completed") else: logger.error("❌ Database creation failed") return False # Step 2: Setup RLS and multi-tenancy if await setup_row_level_security(): logger.info("✅ Multi-tenancy setup completed") else: logger.error("❌ Multi-tenancy setup failed") return False # Step 3: Create performance indexes if await create_indexes(): logger.info("✅ Performance optimization completed") else: logger.error("❌ Performance optimization failed") return False logger.info("🎉 PostgreSQL setup completed successfully!") logger.info("📋 Next steps:") logger.info(" 1. Update .env file with PostgreSQL connection details") logger.info(" 2. Run: python main.py migrate") logger.info(" 3. Start the platform: python main.py serve") return True if __name__ == "__main__": asyncio.run(main())