Spaces:
Runtime error
Runtime error
Create database/connection.py
Browse files- utils/database/connection.py +58 -0
utils/database/connection.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# filename: database/connection.py
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from motor.motor_asyncio import AsyncIOMotorClient
|
| 5 |
+
import config
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
class Database:
|
| 10 |
+
"""
|
| 11 |
+
Manages connections to one or more MongoDB databases.
|
| 12 |
+
"""
|
| 13 |
+
def __init__(self, uris: list[str]):
|
| 14 |
+
if not uris:
|
| 15 |
+
raise ValueError("At least one MongoDB URI is required.")
|
| 16 |
+
|
| 17 |
+
self.clients = [AsyncIOMotorClient(uri) for uri in uris]
|
| 18 |
+
self.databases = [client.get_default_database() for client in self.clients]
|
| 19 |
+
|
| 20 |
+
# For data that should not be split (like cache), we use the first DB as the primary.
|
| 21 |
+
self.primary_db = self.databases[0]
|
| 22 |
+
|
| 23 |
+
# For distributing new users, we'll cycle through the available databases.
|
| 24 |
+
self._user_db_round_robin_counter = 0
|
| 25 |
+
|
| 26 |
+
logger.info(f"Successfully connected to {len(self.clients)} MongoDB database(s).")
|
| 27 |
+
|
| 28 |
+
async def get_user_db(self, user_id: int):
|
| 29 |
+
"""
|
| 30 |
+
Gets the database assigned to a specific user.
|
| 31 |
+
This ensures a user's data always stays in the same database.
|
| 32 |
+
We use a simple hashing method to distribute users.
|
| 33 |
+
"""
|
| 34 |
+
db_index = user_id % len(self.databases)
|
| 35 |
+
return self.databases[db_index]
|
| 36 |
+
|
| 37 |
+
async def find_user_db(self, user_id: int):
|
| 38 |
+
"""
|
| 39 |
+
Searches across all databases to find which one contains the user.
|
| 40 |
+
Returns the database object if found, otherwise None.
|
| 41 |
+
"""
|
| 42 |
+
for db in self.databases:
|
| 43 |
+
if await db.users.find_one({"user_id": user_id}):
|
| 44 |
+
return db
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
def get_next_db_for_new_user(self):
|
| 48 |
+
"""
|
| 49 |
+
Picks a database for a new user using a round-robin strategy.
|
| 50 |
+
This helps distribute new users evenly.
|
| 51 |
+
"""
|
| 52 |
+
db = self.databases[self._user_db_round_robin_counter]
|
| 53 |
+
self._user_db_round_robin_counter = (self._user_db_round_robin_counter + 1) % len(self.databases)
|
| 54 |
+
return db
|
| 55 |
+
|
| 56 |
+
# --- Initialize the Database Connection ---
|
| 57 |
+
# This single `db` object will be imported and used by the rest of the application.
|
| 58 |
+
db = Database(config.MONGODB_URIS)
|