| import pymongo | |
| import urllib.parse | |
| import os | |
| def create_db(): | |
| """ | |
| Connect to MongoDB Atlas and create collections for the Billing App. | |
| """ | |
| raw_username = os.getenv("DB_USERNAME") | |
| raw_password = os.getenv("DB_PASSWORD") | |
| if not raw_username or not raw_password: | |
| raise Exception("Database credentials are missing. Check your environment variables.") | |
| cluster = "cluster0" | |
| username = urllib.parse.quote_plus(raw_username) | |
| password = urllib.parse.quote_plus(raw_password) | |
| uri = f"mongodb+srv://{username}:{password}@cluster0.yxjok.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0" | |
| client = pymongo.MongoClient(uri) | |
| db = client["billing_app"] | |
| users_coll = db["users"] | |
| sections_coll = db["sections"] | |
| bills_coll = db["bills"] | |
| users_coll.create_index("email", unique=True) | |
| sections_coll.create_index( | |
| [("owner_email", 1), ("section_name", 1)], | |
| unique=True | |
| ) | |
| bills_coll.create_index( | |
| [("owner_email", 1), ("section_name", 1), ("participant", 1)] | |
| ) | |
| print("Database and collections created (or already exist). Indexes applied.") | |
| if __name__ == "__main__": | |
| create_db() | |