File size: 9,377 Bytes
372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 579285c 372384b 0743ddc 372384b 579285c 0743ddc 579285c 0743ddc 579285c 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b 0743ddc 372384b | 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | """
YAZ Care Platform - Query Optimization Utilities
Provides database query optimization and caching strategies
"""
import asyncio
import hashlib
import json
import time
from datetime import datetime, timedelta
from functools import lru_cache, wraps
from typing import Any, Callable, Dict, List, Optional
# ==============================================
# QUERY CACHING
# ==============================================
class QueryCache:
"""In-memory cache for database queries with TTL support"""
def __init__(self, max_size: int = 1000, default_ttl: int = 300):
self._cache: dict[str, dict[str, Any]] = {}
self._max_size = max_size
self._default_ttl = default_ttl
self._hits = 0
self._misses = 0
def _generate_key(self, func_name: str, args: tuple, kwargs: dict) -> str:
"""Generate cache key from function name and arguments"""
key_data = {"func": func_name, "args": str(args), "kwargs": str(sorted(kwargs.items()))}
key_str = json.dumps(key_data, sort_keys=True)
return hashlib.md5(key_str.encode()).hexdigest()
def get(self, key: str) -> Any | None:
"""Get value from cache if not expired"""
if key in self._cache:
entry = self._cache[key]
if entry["expires_at"] > datetime.now():
self._hits += 1
return entry["value"]
else:
del self._cache[key]
self._misses += 1
return None
def set(self, key: str, value: Any, ttl: int | None = None) -> None:
"""Set value in cache with TTL"""
if len(self._cache) >= self._max_size:
# Remove oldest entry
oldest_key = min(self._cache.keys(), key=lambda k: self._cache[k]["created_at"])
del self._cache[oldest_key]
ttl = ttl or self._default_ttl
self._cache[key] = {
"value": value,
"created_at": datetime.now(),
"expires_at": datetime.now() + timedelta(seconds=ttl),
}
def invalidate(self, pattern: str | None = None) -> int:
"""Invalidate cache entries matching pattern"""
if pattern is None:
count = len(self._cache)
self._cache.clear()
return count
keys_to_remove = [k for k in self._cache.keys() if pattern in k]
for key in keys_to_remove:
del self._cache[key]
return len(keys_to_remove)
def get_stats(self) -> dict[str, Any]:
"""Get cache statistics"""
total_requests = self._hits + self._misses
hit_rate = (self._hits / total_requests * 100) if total_requests > 0 else 0
return {
"size": len(self._cache),
"max_size": self._max_size,
"hits": self._hits,
"misses": self._misses,
"hit_rate": f"{hit_rate:.2f}%",
"total_requests": total_requests,
}
# Global query cache instance
_query_cache = QueryCache(max_size=2000, default_ttl=300)
def cached_query(ttl: int = 300):
"""Decorator for caching database query results"""
def decorator(func: Callable) -> Callable:
@wraps(func)
async def async_wrapper(*args, **kwargs):
cache_key = _query_cache._generate_key(func.__name__, args, kwargs)
# Try to get from cache
cached_result = _query_cache.get(cache_key)
if cached_result is not None:
return cached_result
# Execute query and cache result
result = await func(*args, **kwargs)
_query_cache.set(cache_key, result, ttl)
return result
@wraps(func)
def sync_wrapper(*args, **kwargs):
cache_key = _query_cache._generate_key(func.__name__, args, kwargs)
# Try to get from cache
cached_result = _query_cache.get(cache_key)
if cached_result is not None:
return cached_result
# Execute query and cache result
result = func(*args, **kwargs)
_query_cache.set(cache_key, result, ttl)
return result
# Return appropriate wrapper based on whether function is async
if asyncio.iscoroutinefunction(func):
return async_wrapper
else:
return sync_wrapper
return decorator
def invalidate_cache(pattern: str | None = None) -> int:
"""Invalidate cached queries"""
return _query_cache.invalidate(pattern)
def get_cache_stats() -> dict[str, Any]:
"""Get query cache statistics"""
return _query_cache.get_stats()
# ==============================================
# QUERY OPTIMIZATION HELPERS
# ==============================================
def optimize_query_batch_size(total_items: int, max_batch_size: int = 100) -> int:
"""Calculate optimal batch size for query operations"""
if total_items <= 10:
return total_items
elif total_items <= 100:
return min(20, total_items)
elif total_items <= 1000:
return min(50, total_items)
else:
return max_batch_size
async def batch_query_executor(
items: list[Any],
query_func: Callable,
batch_size: int | None = None,
delay_between_batches: float = 0.01,
) -> list[Any]:
"""
Execute queries in batches to prevent overwhelming the database
Args:
items: List of items to query
query_func: Async function to execute for each item
batch_size: Size of each batch (auto-calculated if None)
delay_between_batches: Delay in seconds between batches
Returns:
List of query results
"""
if not items:
return []
if batch_size is None:
batch_size = optimize_query_batch_size(len(items))
results = []
for i in range(0, len(items), batch_size):
batch = items[i : i + batch_size]
batch_results = await asyncio.gather(*[query_func(item) for item in batch])
results.extend(batch_results)
# Small delay to prevent overwhelming the database
if i + batch_size < len(items):
await asyncio.sleep(delay_between_batches)
return results
# ==============================================
# QUERY TIMING
# ==============================================
class QueryTimer:
"""Context manager for timing query execution"""
def __init__(
self, query_name: str, log_slow_queries: bool = True, slow_query_threshold: float = 1.0
):
self.query_name = query_name
self.log_slow_queries = log_slow_queries
self.slow_query_threshold = slow_query_threshold
self.start_time = None
self.duration = None
def __enter__(self):
self.start_time = time.time() # type: ignore[arg-type, assignment]
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.duration = time.time() - self.start_time # type: ignore[assignment, misc, operator, valid-type]
if self.log_slow_queries and self.duration > self.slow_query_threshold: # type: ignore[misc, operator, valid-type]
import structlog
logger = structlog.get_logger(__name__)
logger.warning(f"Slow query detected: {self.query_name} took {self.duration:.3f}s")
def timed_query(slow_threshold: float = 1.0):
"""Decorator for timing query execution"""
def decorator(func: Callable) -> Callable:
@wraps(func)
async def async_wrapper(*args, **kwargs):
with QueryTimer(func.__name__, slow_query_threshold=slow_threshold):
return await func(*args, **kwargs)
@wraps(func)
def sync_wrapper(*args, **kwargs):
with QueryTimer(func.__name__, slow_query_threshold=slow_threshold):
return func(*args, **kwargs)
if asyncio.iscoroutinefunction(func):
return async_wrapper
else:
return sync_wrapper
return decorator
# ==============================================
# CONNECTION POOL OPTIMIZATION
# ==============================================
def get_optimal_pool_settings(environment: str = "development") -> dict[str, int]:
"""
Get optimal database connection pool settings based on environment
Returns:
Dictionary with pool_size, max_overflow, pool_timeout, pool_recycle
"""
settings = {
"development": {
"pool_size": 5,
"max_overflow": 10,
"pool_timeout": 30,
"pool_recycle": 3600,
"pool_pre_ping": True,
},
"staging": {
"pool_size": 10,
"max_overflow": 20,
"pool_timeout": 30,
"pool_recycle": 3600,
"pool_pre_ping": True,
},
"production": {
"pool_size": 20,
"max_overflow": 40,
"pool_timeout": 30,
"pool_recycle": 1800,
"pool_pre_ping": True,
},
}
return settings.get(environment, settings["production"])
# ==============================================
# EXPORTS
# ==============================================
__all__ = [
"QueryCache",
"cached_query",
"invalidate_cache",
"get_cache_stats",
"optimize_query_batch_size",
"batch_query_executor",
"QueryTimer",
"timed_query",
"get_optimal_pool_settings",
]
|