Coverage for dao/base_dao.py: 65.19%

153 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 15:03 +0000

1""" 

2Base Data Access Object for MissingTable. 

3 

4Provides common functionality and connection management for all DAOs. 

5All domain-specific DAOs should inherit from BaseDAO. 

6 

7## Caching 

8 

9Two decorators provide clean caching for DAO methods: 

10 

11### @dao_cache - Cache read operations 

12 

13 @dao_cache("teams:all") 

14 def get_all_teams(self): 

15 return self.client.table("teams").select("*").execute().data 

16 

17 @dao_cache("teams:club:{club_id}") 

18 def get_club_teams(self, club_id: int): 

19 return self.client.table("teams").eq("club_id", club_id).execute().data 

20 

21The decorator: 

221. Builds cache key from pattern (substituting {arg_name} with actual values) 

232. Checks Redis - returns cached data if found 

243. On miss - runs method, caches result, returns it 

25 

26### @invalidates_cache - Clear cache after writes 

27 

28 @invalidates_cache("mt:dao:teams:*") 

29 def add_team(self, name: str, city: str): 

30 return self.client.table("teams").insert({...}).execute() 

31 

32After successful completion, clears all keys matching the pattern(s). 

33""" 

34 

35import functools 

36import inspect 

37import json 

38import os 

39from typing import TYPE_CHECKING 

40 

41import structlog 

42 

43if TYPE_CHECKING: 

44 from supabase import Client 

45 

46logger = structlog.get_logger() 

47 

48# SB-591 Phase 2 test partition. Match READS go through this view, which carries 

49# a derived is_test flag (the match's league, tournament, either club, or either 

50# team's league is is_test); WRITES stay on the "matches" table. Embedded selects 

51# resolve identically from either relation, so callers swap only the relation 

52# name and add `.eq("is_test", False)` for non-test viewers. Defined here rather 

53# than in match_dao so every DAO can share it without importing match_dao. 

54MATCHES_READ_RELATION = "matches_with_test" 

55 

56# Every first segment of an `mt:dao:<type>:...` key. GET /api/admin/cache groups 

57# keys by this segment and DELETE /api/admin/cache/{type} only clears names on 

58# this list, so a namespace missing here shows up in the admin view with no way 

59# to clear it on its own (SB-1278). test_cache_types.py fails when a DAO starts 

60# writing a namespace that is not listed. 

61CACHE_TYPES = frozenset( 

62 { 

63 "admin_attention", 

64 "age_groups", 

65 "clubs", 

66 "divisions", 

67 "email_messages", 

68 "email_threads", 

69 "leagues", 

70 "lineup", 

71 "match_types", 

72 "matches", 

73 "players", 

74 "playoffs", 

75 "power_rating", 

76 "qop", 

77 "roster", 

78 "seasons", 

79 "stats", 

80 "teams", 

81 "tournaments", 

82 } 

83) 

84 

85# Names the admin endpoint accepted before CACHE_TYPES existed, mapped to the key 

86# prefix they actually mean. "rosters" never matched the DAO's "roster" keys, and 

87# standings are cached under matches; both are kept so existing clients 

88# (AdminCache.vue, mt-dt) keep working, now deleting what they name. 

89CACHE_TYPE_ALIASES = { 

90 "rosters": "roster", 

91 "standings": "matches:standings", 

92} 

93 

94# Shared Redis client for all DAOs 

95_redis_client = None 

96 

97 

98def get_redis_client(): 

99 """Get sync Redis client for DAO-level caching. 

100 

101 Returns a shared Redis client instance, or None if caching is disabled 

102 or Redis is unavailable. Gracefully degrades - app continues without cache. 

103 """ 

104 global _redis_client 

105 if _redis_client is not None: 105 ↛ 106line 105 didn't jump to line 106 because the condition on line 105 was never true

106 return _redis_client 

107 

108 if os.getenv("CACHE_ENABLED", "false").lower() != "true": 108 ↛ 111line 108 didn't jump to line 111 because the condition on line 108 was always true

109 return None 

110 

111 try: 

112 import redis 

113 

114 url = os.getenv("REDIS_URL", "redis://localhost:6379/0") 

115 _redis_client = redis.from_url(url, decode_responses=True) 

116 _redis_client.ping() 

117 return _redis_client 

118 except Exception as e: 

119 logger.warning("dao_redis_connection_failed", error=str(e)) 

120 return None 

121 

122 

123def clear_cache(pattern: str) -> int: 

124 """Clear cache entries matching a pattern. 

125 

126 Args: 

127 pattern: Redis key pattern (e.g., "mt:dao:clubs:*") 

128 

129 Returns: 

130 Number of keys deleted 

131 """ 

132 redis_client = get_redis_client() 

133 if not redis_client: 

134 return 0 

135 try: 

136 cursor = 0 

137 deleted = 0 

138 while True: 

139 cursor, keys = redis_client.scan(cursor, match=pattern, count=100) 

140 if keys: 

141 deleted += redis_client.delete(*keys) 

142 if cursor == 0: 142 ↛ 138line 142 didn't jump to line 138 because the condition on line 142 was always true

143 break 

144 if deleted > 0: 

145 logger.info("dao_cache_cleared", pattern=pattern, deleted=deleted) 

146 return deleted 

147 except Exception as e: 

148 logger.warning("dao_cache_clear_error", pattern=pattern, error=str(e)) 

149 return 0 

150 

151 

152def cache_get(key: str): 

153 """Get a value from cache. 

154 

155 Args: 

156 key: Cache key 

157 

158 Returns: 

159 Deserialized value or None if not found/error 

160 """ 

161 redis_client = get_redis_client() 

162 if not redis_client: 

163 return None 

164 try: 

165 cached = redis_client.get(key) 

166 if cached: 

167 logger.info("dao_cache_hit", key=key) 

168 return json.loads(cached) 

169 except Exception as e: 

170 logger.warning("dao_cache_get_error", key=key, error=str(e)) 

171 return None 

172 

173 

174def cache_set(key: str, value, ttl: int = 86400) -> bool: 

175 """Set a value in cache. 

176 

177 Args: 

178 key: Cache key 

179 value: Value to cache (will be JSON serialized) 

180 ttl: Time to live in seconds (default 24 hours) 

181 

182 Returns: 

183 True if successful, False otherwise 

184 """ 

185 redis_client = get_redis_client() 

186 if not redis_client: 

187 return False 

188 try: 

189 redis_client.setex(key, ttl, json.dumps(value, default=str)) 

190 logger.info("dao_cache_set", key=key) 

191 return True 

192 except Exception as e: 

193 logger.warning("dao_cache_set_error", key=key, error=str(e)) 

194 return False 

195 

196 

197# ============================================================================= 

198# CACHING DECORATORS 

199# ============================================================================= 

200 

201 

202def dao_cache(key_pattern: str, ttl: int = 86400): 

203 """Decorator to cache DAO method results. 

204 

205 Args: 

206 key_pattern: Cache key pattern with optional {arg} placeholders. 

207 e.g., "teams:all" or "teams:club:{club_id}" 

208 ttl: Time to live in seconds (default 24 hours) 

209 

210 Example: 

211 @dao_cache("teams:club:{club_id}") 

212 def get_club_teams(self, club_id: int): 

213 return self.client.table("teams").eq("club_id", club_id).execute().data 

214 

215 How it works: 

216 1. When get_club_teams(club_id=5) is called 

217 2. Decorator builds key: "mt:dao:teams:club:5" 

218 3. Checks Redis for cached data 

219 4. If found: returns cached data (method never runs) 

220 5. If not found: runs method, caches result, returns it 

221 """ 

222 

223 def decorator(func): 

224 @functools.wraps(func) 

225 def wrapper(self, *args, **kwargs): 

226 # Build cache key by substituting {arg_name} with actual values 

227 # Get parameter names from function signature (skip 'self') 

228 sig = inspect.signature(func) 

229 param_names = list(sig.parameters.keys())[1:] 

230 

231 # Map positional args to their names 

232 key_values = dict(zip(param_names, args, strict=False)) 

233 key_values.update(kwargs) 

234 

235 # Build full cache key: mt:dao:{pattern with substitutions} 

236 try: 

237 cache_key = f"mt:dao:{key_pattern.format(**key_values)}" 

238 except KeyError as e: 

239 # If pattern has placeholder not in args, skip caching 

240 logger.warning("dao_cache_key_error", pattern=key_pattern, missing=str(e)) 

241 return func(self, *args, **kwargs) 

242 

243 # Try to get from cache 

244 cached = cache_get(cache_key) 

245 if cached is not None: 

246 return cached 

247 

248 # Cache miss - run the actual method 

249 logger.debug("dao_cache_miss", key=cache_key, method=func.__name__) 

250 result = func(self, *args, **kwargs) 

251 

252 # Cache the result (only if not None) 

253 if result is not None: 

254 cache_set(cache_key, result, ttl) 

255 

256 return result 

257 

258 return wrapper 

259 

260 return decorator 

261 

262 

263def invalidates_cache(*patterns: str): 

264 """Decorator to clear cache after a write operation succeeds. 

265 

266 Args: 

267 *patterns: One or more cache key patterns to clear. 

268 e.g., "mt:dao:teams:*", "mt:dao:clubs:*" 

269 

270 Example: 

271 @invalidates_cache("mt:dao:teams:*") 

272 def add_team(self, name: str, city: str): 

273 return self.client.table("teams").insert({...}).execute() 

274 

275 @invalidates_cache("mt:dao:teams:*", "mt:dao:clubs:*") 

276 def update_team_club(self, team_id: int, club_id: int): 

277 ... 

278 

279 How it works: 

280 1. Runs the wrapped method 

281 2. If successful (no exception), clears all keys matching each pattern 

282 3. Returns the method's result 

283 """ 

284 

285 def decorator(func): 

286 @functools.wraps(func) 

287 def wrapper(self, *args, **kwargs): 

288 # Run the actual method first 

289 result = func(self, *args, **kwargs) 

290 

291 # On success, invalidate cache patterns 

292 for pattern in patterns: 

293 clear_cache(pattern) 

294 

295 return result 

296 

297 return wrapper 

298 

299 return decorator 

300 

301 

302class BaseDAO: 

303 """Base DAO with shared connection logic and common utilities.""" 

304 

305 def __init__(self, connection_holder): 

306 """ 

307 Initialize with a SupabaseConnection. 

308 

309 Args: 

310 connection_holder: SupabaseConnection instance 

311 

312 Raises: 

313 TypeError: If connection_holder is not a SupabaseConnection 

314 """ 

315 from dao.match_dao import SupabaseConnection 

316 

317 if not isinstance(connection_holder, SupabaseConnection): 

318 raise TypeError("connection_holder must be a SupabaseConnection instance") 

319 

320 self.connection_holder = connection_holder 

321 self.client: Client = connection_holder.get_client() 

322 

323 def execute_query(self, query, operation_name: str = "database operation"): 

324 """ 

325 Execute a Supabase query with common error handling. 

326 

327 Args: 

328 query: Supabase query object (result of .select(), .insert(), etc.) 

329 operation_name: Description of the operation for logging 

330 

331 Returns: 

332 Query response data 

333 

334 Raises: 

335 Exception: Re-raises any database errors after logging 

336 """ 

337 try: 

338 response = query.execute() 

339 return response 

340 except Exception as e: 

341 logger.exception( 

342 f"Error during {operation_name}", 

343 operation=operation_name, 

344 error_type=type(e).__name__, 

345 error_message=str(e), 

346 ) 

347 raise 

348 

349 def safe_execute(self, query, operation_name: str = "database operation", default=None): 

350 """ 

351 Execute a query with error handling that returns a default value on error. 

352 

353 Useful for non-critical queries where you want to continue execution 

354 even if the query fails. 

355 

356 Args: 

357 query: Supabase query object 

358 operation_name: Description of the operation for logging 

359 default: Value to return if query fails (default: None) 

360 

361 Returns: 

362 Query response data or default value on error 

363 """ 

364 try: 

365 response = query.execute() 

366 return response 

367 except Exception as e: 

368 logger.warning( 

369 f"Non-critical error during {operation_name}", 

370 operation=operation_name, 

371 error_type=type(e).__name__, 

372 error_message=str(e), 

373 returning_default=default, 

374 ) 

375 return default 

376 

377 def get_by_id(self, table: str, record_id: int, id_field: str = "id") -> dict | None: 

378 """ 

379 Generic method to get a single record by ID. 

380 

381 Args: 

382 table: Table name 

383 record_id: Record ID to fetch 

384 id_field: Name of the ID field (default: "id") 

385 

386 Returns: 

387 dict: Record data or None if not found 

388 

389 Raises: 

390 Exception: If database query fails 

391 """ 

392 try: 

393 response = self.client.table(table).select("*").eq(id_field, record_id).execute() 

394 return response.data[0] if response.data else None 

395 except Exception: 

396 logger.exception( 

397 f"Error fetching record from {table}", 

398 table=table, 

399 record_id=record_id, 

400 id_field=id_field, 

401 ) 

402 raise 

403 

404 def get_all(self, table: str, order_by: str | None = None) -> list[dict]: 

405 """ 

406 Generic method to get all records from a table. 

407 

408 Args: 

409 table: Table name 

410 order_by: Optional field name to order by 

411 

412 Returns: 

413 list[dict]: List of records 

414 

415 Raises: 

416 Exception: If database query fails 

417 """ 

418 try: 

419 query = self.client.table(table).select("*") 

420 if order_by: 

421 query = query.order(order_by) 

422 response = query.execute() 

423 return response.data 

424 except Exception: 

425 logger.exception(f"Error fetching all records from {table}", table=table, order_by=order_by) 

426 raise 

427 

428 def exists(self, table: str, field: str, value) -> bool: 

429 """ 

430 Check if a record exists with the given field value. 

431 

432 Args: 

433 table: Table name 

434 field: Field name to check 

435 value: Value to match 

436 

437 Returns: 

438 bool: True if record exists, False otherwise 

439 """ 

440 try: 

441 response = self.client.table(table).select("id").eq(field, value).limit(1).execute() 

442 return len(response.data) > 0 

443 except Exception: 

444 logger.exception(f"Error checking existence in {table}", table=table, field=field, value=value) 

445 return False 

446 

447 def delete_by_id(self, table: str, record_id: int, id_field: str = "id") -> bool: 

448 """ 

449 Generic method to delete a record by ID. 

450 

451 Args: 

452 table: Table name 

453 record_id: Record ID to delete 

454 id_field: Name of the ID field (default: "id") 

455 

456 Returns: 

457 bool: True if successful, False otherwise 

458 """ 

459 try: 

460 self.client.table(table).delete().eq(id_field, record_id).execute() 

461 logger.info(f"Deleted record from {table}", table=table, record_id=record_id) 

462 return True 

463 except Exception: 

464 logger.exception(f"Error deleting record from {table}", table=table, record_id=record_id) 

465 return False