Download src/core/database/query_optimizer.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 9.38 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/database/query_optimizer.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/database/query_optimizer.py
-
curl -L -o query_optimizer.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/database/query_optimizer.py
9.38 kB
| """ | |
| 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: | |
| 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 | |
| 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: | |
| async def async_wrapper(*args, **kwargs): | |
| with QueryTimer(func.__name__, slow_query_threshold=slow_threshold): | |
| return await func(*args, **kwargs) | |
| 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", | |
| ] | |