import os import certifi from pymongo import MongoClient from pymongo.errors import ConnectionFailure from src.logger import logging # Importing your custom logger # Use environment variables for deployment, falling back to localhost for local testing MONGO_URI = os.getenv("MONGO_URI", "mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.5.1") DB_NAME = os.getenv("DB_NAME", "Rankmate") class Database: def __init__(self): self.client=None self.db=None def connect(self): try: logging.info(f"Connecting to MongoDB client: {MONGO_URI}") # Smart TLS Handling: Don't use TLS/SSL for local development to prevent Handshake errors if "127.0.0.1" in MONGO_URI or "localhost" in MONGO_URI: self.client = MongoClient(MONGO_URI) else: self.client = MongoClient(MONGO_URI, tlsCAFile=certifi.where()) self.client.admin.command('ping') self.db=self.client[DB_NAME] logging.info(f"Successfully connected to database: {DB_NAME}") self._setup_indexes() except ConnectionFailure as e: logging.error(f"Failed to connect to the Mongo Client: {MONGO_URI}") raise e def get_db(self): if self.db is None: self.connect() return self.db def close(self): if self.client: self.client.close() logging.info(f"Succesfully closed the connection with mongo client: {MONGO_URI}") def _setup_indexes(self): """Creates the required compound indexes for scale and multi-tenant performance.""" try: # 1. schools collection self.db.schools.create_index("udise_number", unique=True) # Enforce unique UDISE numbers self.db.schools.create_index("name") # 2. academic_records collection (The Fact Table) # --- NEW: Unique compound index to supercharge upserts and prevent duplicates --- self.db.academic_records.create_index( [("school_id", 1), ("student_id", 1), ("subject_id", 1)], unique=True, name="unique_student_subject_idx" ) # These are the compound indexes required for lightning-fast dashboard queries self.db.academic_records.create_index([("school_id", 1)]) self.db.academic_records.create_index([("school_id", 1), ("teacher_id", 1)]) # Indexes including academic_year and semester to handle the batch tracking cleanly self.db.academic_records.create_index([("school_id", 1), ("academic_year", 1), ("class_id", 1)]) self.db.academic_records.create_index([("school_id", 1), ("academic_year", 1), ("semester", 1)]) logging.info("Successfully verified/created database indexes.") except Exception as e: logging.error(f"Error setting up indexes: {e}") db_instance=Database()