Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
214 lines (182 loc) · 6.23 KB
/
Copy pathdatabase.py
File metadata and controls
214 lines (182 loc) · 6.23 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import json
import mysql.connector
from mysql.connector import Error, pooling
from contextlib import contextmanager
from typing import Optional, List, Dict, Any
from config import DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME
# ============================================================
# Connection Pool
# ============================================================
# A pool of 5 reusable connections avoids the overhead of
# opening a new TCP connection on every request.
# ============================================================
_pool: Optional[pooling.MySQLConnectionPool] = None
def _get_pool() -> pooling.MySQLConnectionPool:
"""Lazily create and return the shared connection pool."""
global _pool
if _pool is None:
_pool = pooling.MySQLConnectionPool(
pool_name="biosentinel_pool",
pool_size=5,
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME,
autocommit=False,
charset="utf8mb4",
collation="utf8mb4_unicode_ci",
)
return _pool
@contextmanager
def get_db():
"""
Context manager that yields a live MySQL connection from the pool.
Commits on success, rolls back on exception, always returns the
connection to the pool when the block exits.
Usage:
with get_db() as conn:
cursor = conn.cursor(dictionary=True)
cursor.execute(...)
"""
conn = _get_pool().get_connection()
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
# ============================================================
# Helper Functions
# ============================================================
def db_execute(query: str, values: Optional[tuple] = None) -> bool:
"""Run INSERT / UPDATE / DELETE. Returns True on success."""
with get_db() as conn:
cursor = conn.cursor()
cursor.execute(query, values)
return True
def db_insert(query: str, values: Optional[tuple] = None) -> Optional[int]:
"""
Run an INSERT and return the last-inserted row ID.
Returns None on failure.
"""
with get_db() as conn:
cursor = conn.cursor()
cursor.execute(query, values)
return cursor.lastrowid
def db_fetch_one(query: str, values: Optional[tuple] = None) -> Optional[Dict[str, Any]]:
"""Return a single row as a dict, or None."""
with get_db() as conn:
cursor = conn.cursor(dictionary=True)
cursor.execute(query, values)
return cursor.fetchone()
def db_fetch_all(query: str, values: Optional[tuple] = None) -> List[Dict[str, Any]]:
"""Return all matching rows as a list of dicts."""
with get_db() as conn:
cursor = conn.cursor(dictionary=True)
cursor.execute(query, values)
return cursor.fetchall()
# ============================================================
# Database Initialization
# ============================================================
def init_db() -> None:
"""
Run the full schema SQL from database.sql.
Called once at startup (or from Flask CLI).
Safe to call multiple times — uses IF NOT EXISTS guards.
"""
import os
sql_path = os.path.join(os.path.dirname(__file__), "database.sql")
with open(sql_path, "r") as f:
raw = f.read()
# Split on semicolons to execute statement-by-statement
statements = [s.strip() for s in raw.split(";") if s.strip()]
# Use a direct connection (not the pool) for DDL
conn = mysql.connector.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME,
charset="utf8mb4",
)
cursor = conn.cursor()
for stmt in statements:
try:
cursor.execute(stmt)
except Error as e:
# Log but don't crash on duplicate-table warnings
print(f"[DB] Warning: {e}")
conn.commit()
cursor.close()
conn.close()
print("[DB] Schema initialized.")
# ============================================================
# Legacy Class Wrapper (backwards-compatible with old code)
# ============================================================
class Database:
"""
Thin wrapper kept for backward compatibility with any
code that uses Database().connect() / .execute() etc.
New code should use the module-level helper functions above.
"""
def __init__(self):
self.connection = None
def connect(self):
try:
self.connection = mysql.connector.connect(
host=DB_HOST, port=DB_PORT,
user=DB_USER, password=DB_PASSWORD,
database=DB_NAME
)
except Error as e:
print(f"[DB] Error: {e}")
def disconnect(self):
if self.connection and self.connection.is_connected():
self.connection.close()
def execute(self, query, values=None):
cursor = self.connection.cursor()
try:
cursor.execute(query, values)
self.connection.commit()
return True
except Error as e:
print(e)
self.connection.rollback()
return False
finally:
cursor.close()
def execute_lastrowid(self, query, values=None):
cursor = self.connection.cursor()
try:
cursor.execute(query, values)
self.connection.commit()
return cursor.lastrowid
except Error as e:
print(e)
self.connection.rollback()
return None
finally:
cursor.close()
def fetch_one(self, query, values=None):
cursor = self.connection.cursor(dictionary=True)
try:
cursor.execute(query, values)
return cursor.fetchone()
except Error as e:
print(e)
return None
finally:
cursor.close()
def fetch_all(self, query, values=None):
cursor = self.connection.cursor(dictionary=True)
try:
cursor.execute(query, values)
return cursor.fetchall()
except Error as e:
print(e)
return []
finally:
cursor.close()