-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
101 lines (82 loc) · 2.83 KB
/
database.py
File metadata and controls
101 lines (82 loc) · 2.83 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from pymongo import MongoClient
import os
from dotenv import load_dotenv
import threading
import time
load_dotenv()
# Determine certificate path and TLS usage
if os.getenv("STAGE") == "local":
file_name = "ca-certificate.crt"
use_tls = os.getenv("MONGO_URI") != "mongodb://localhost:27017/"
else:
file_name = "/etc/ssl/ca-certificate.crt"
use_tls = True
# Initialize MongoDB client
if use_tls:
client = MongoClient(
os.getenv("MONGO_URI"),
tls=True,
tlsCAFile=file_name,
)
else:
client = MongoClient(os.getenv("MONGO_URI"))
# Force connection on startup
try:
client.admin.command("ping")
print("✅ MongoDB connection successful on startup")
except Exception as e:
print(f"❌ MongoDB connection failed on startup: {e}")
raise e
# Start a keep-alive thread
def keep_connection_alive():
while True:
try:
client.admin.command("ping")
print("🔁 MongoDB keep-alive ping successful")
except Exception as e:
print(f"⚠️ MongoDB keep-alive ping failed: {e}")
time.sleep(300) # ping every 5 minutes
threading.Thread(target=keep_connection_alive, daemon=True).start()
# Access the database
db = client[os.getenv("MONGO_DB", "score_db")]
daily_sun_db = client[os.getenv("DAILY_SUN_DB", "daily_sun_db")]
def setup_database_indexes():
"""Set up MongoDB indexes for optimal query performance"""
try:
game_collection = db["game"]
# Create single field indexes for commonly queried fields
game_collection.create_index([("sport", 1)], background=True)
game_collection.create_index([("date", 1)], background=True)
game_collection.create_index([("gender", 1)], background=True)
# Create compound indexes for common query combinations
game_collection.create_index([("sport", 1), ("gender", 1)], background=True)
# Index for sorting operations
game_collection.create_index([("date", -1)], background=True)
# Index to have unique games so we won't add duplicates
game_collection.create_index(
[
("sport", 1),
("gender", 1),
("date", 1),
("opponent_id", 1),
("state", 1),
],
unique=True,
background=True
)
# Additional index for tournament games (without opponent_id)
game_collection.create_index(
[
("sport", 1),
("gender", 1),
("date", 1),
("city", 1),
("state", 1),
],
background=True
)
print("✅ MongoDB indexes created successfully")
except Exception as e:
print(f"❌ Failed to create MongoDB indexes: {e}")
raise e
setup_database_indexes()