File size: 3,138 Bytes
f7531d8 7e03cc0 f7531d8 7e03cc0 f7531d8 0fc32ad f7531d8 7e03cc0 f7531d8 7e03cc0 f7531d8 7e03cc0 f7531d8 7e03cc0 f7531d8 7e03cc0 f7531d8 7e03cc0 f7531d8 48322a4 | 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 | 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() |