Download src/middleware/query_profiler.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/middleware/query_profiler.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/middleware/query_profiler.py
-
curl -L -o query_profiler.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/middleware/query_profiler.py
14.1 kB
| """ | |
| Query Profiling Middleware | |
| Sprint 30 Task 30.3: Detect and log slow database queries | |
| This middleware monitors all database queries and: | |
| 1. Logs slow queries (>threshold) | |
| 2. Detects N+1 query patterns | |
| 3. Tracks query frequency | |
| 4. Generates performance reports | |
| Usage in FastAPI: | |
| app.add_middleware(QueryProfilingMiddleware, slow_query_threshold_ms=10) | |
| """ | |
| import time | |
| from collections import defaultdict | |
| from contextlib import contextmanager | |
| from datetime import UTC, datetime, timedelta, timezone | |
| from typing import Dict, List, Optional | |
| import structlog | |
| from prometheus_client import Counter, Gauge, Histogram | |
| from sqlalchemy import event | |
| from sqlalchemy.engine import Engine | |
| logger = structlog.get_logger(__name__) | |
| # ============================================================================= | |
| # Prometheus Metrics | |
| # ============================================================================= | |
| db_query_duration = Histogram( | |
| "db_query_duration_seconds", | |
| "Database query execution time", | |
| ["query_type", "table"], | |
| buckets=(0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0), | |
| ) | |
| db_query_count = Counter( | |
| "db_query_count_total", "Total database queries executed", ["query_type", "table"] | |
| ) | |
| db_slow_query_count = Counter( | |
| "db_slow_query_count_total", "Total slow queries (>threshold)", ["query_type", "table"] | |
| ) | |
| db_n_plus_1_detected = Counter( | |
| "db_n_plus_1_detected_total", "N+1 query patterns detected", ["table"] | |
| ) | |
| db_active_connections = Gauge("db_active_connections", "Number of active database connections") | |
| # ============================================================================= | |
| # Query Profiler | |
| # ============================================================================= | |
| class QueryProfiler: | |
| """Profile database queries and detect anti-patterns.""" | |
| def __init__( | |
| self, | |
| slow_query_threshold_ms: float = 10.0, | |
| n_plus_1_threshold: int = 10, | |
| enable_stack_traces: bool = False, | |
| ): | |
| """ | |
| Initialize query profiler. | |
| Args: | |
| slow_query_threshold_ms: Threshold for slow query logging (ms) | |
| n_plus_1_threshold: Number of similar queries to trigger N+1 detection | |
| enable_stack_traces: Capture stack traces for slow queries | |
| """ | |
| self.slow_query_threshold_ms = slow_query_threshold_ms | |
| self.n_plus_1_threshold = n_plus_1_threshold | |
| self.enable_stack_traces = enable_stack_traces | |
| # Query tracking | |
| self._query_stats: dict[str, list[float]] = defaultdict(list) | |
| self._query_patterns: dict[str, int] = defaultdict(int) | |
| self._request_queries: list[dict] = [] | |
| # N+1 detection | |
| self._similar_queries_window = 100 # Check last N queries | |
| self._similar_query_buffer: list[str] = [] | |
| def start_request(self): | |
| """Start tracking queries for a new request.""" | |
| self._request_queries.clear() | |
| def end_request(self) -> dict: | |
| """ | |
| End request and return query statistics. | |
| Returns: | |
| Dict with query count, total time, slow queries | |
| """ | |
| total_queries = len(self._request_queries) | |
| total_time_ms = sum(q["duration_ms"] for q in self._request_queries) | |
| slow_queries = [ | |
| q for q in self._request_queries if q["duration_ms"] > self.slow_query_threshold_ms | |
| ] | |
| # Check for N+1 patterns | |
| n_plus_1_patterns = self._detect_n_plus_1() | |
| stats = { | |
| "total_queries": total_queries, | |
| "total_time_ms": total_time_ms, | |
| "slow_query_count": len(slow_queries), | |
| "slow_queries": slow_queries, | |
| "n_plus_1_patterns": n_plus_1_patterns, | |
| } | |
| return stats | |
| def log_query(self, query_sql: str, duration_ms: float, parameters: tuple | None = None): | |
| """ | |
| Log a database query. | |
| Args: | |
| query_sql: SQL query string | |
| duration_ms: Query execution time in milliseconds | |
| parameters: Query parameters (optional) | |
| """ | |
| # Extract query type and table | |
| query_type, table = self._parse_query(query_sql) | |
| # Record query | |
| query_info = { | |
| "sql": query_sql, | |
| "duration_ms": duration_ms, | |
| "query_type": query_type, | |
| "table": table, | |
| "timestamp": datetime.now(UTC).isoformat(), | |
| "parameters": parameters, | |
| } | |
| self._request_queries.append(query_info) | |
| # Update metrics | |
| db_query_duration.labels(query_type=query_type, table=table).observe(duration_ms / 1000.0) | |
| db_query_count.labels(query_type=query_type, table=table).inc() | |
| # Log slow queries | |
| if duration_ms > self.slow_query_threshold_ms: | |
| db_slow_query_count.labels(query_type=query_type, table=table).inc() | |
| logger.warning( | |
| f"Slow query detected ({duration_ms:.2f}ms): {query_type} on {table}", | |
| extra={ | |
| "query_sql": query_sql[:200], # Truncate long queries | |
| "duration_ms": duration_ms, | |
| "query_type": query_type, | |
| "table": table, | |
| }, | |
| ) | |
| # Track query patterns for N+1 detection | |
| self._track_query_pattern(query_sql) | |
| def _parse_query(self, query_sql: str) -> tuple[str, str]: | |
| """ | |
| Parse SQL query to extract type and table. | |
| Args: | |
| query_sql: SQL query string | |
| Returns: | |
| Tuple of (query_type, table_name) | |
| """ | |
| query_upper = query_sql.upper().strip() | |
| # Determine query type | |
| if query_upper.startswith("SELECT"): | |
| query_type = "SELECT" | |
| elif query_upper.startswith("INSERT"): | |
| query_type = "INSERT" | |
| elif query_upper.startswith("UPDATE"): | |
| query_type = "UPDATE" | |
| elif query_upper.startswith("DELETE"): | |
| query_type = "DELETE" | |
| else: | |
| query_type = "OTHER" | |
| # Extract table name (simplified) | |
| table = "unknown" | |
| try: | |
| if query_type == "SELECT": | |
| # Find FROM clause | |
| from_idx = query_upper.find(" FROM ") | |
| if from_idx != -1: | |
| after_from = query_upper[from_idx + 6 :].strip() | |
| table = after_from.split()[0].strip().lower() | |
| elif query_type == "INSERT": | |
| # Find INTO clause | |
| into_idx = query_upper.find(" INTO ") | |
| if into_idx != -1: | |
| after_into = query_upper[into_idx + 6 :].strip() | |
| table = after_into.split()[0].strip().lower() | |
| elif query_type in ("UPDATE", "DELETE"): | |
| # Find table after UPDATE or DELETE FROM | |
| words = query_upper.split() | |
| if len(words) > 1: | |
| table = words[1 if query_type == "UPDATE" else 2].strip().lower() | |
| except Exception: | |
| pass | |
| return query_type, table | |
| def _track_query_pattern(self, query_sql: str): | |
| """Track query patterns for N+1 detection.""" | |
| # Normalize query (remove parameters) | |
| normalized = self._normalize_query(query_sql) | |
| # Add to buffer | |
| self._similar_query_buffer.append(normalized) | |
| # Keep buffer size limited | |
| if len(self._similar_query_buffer) > self._similar_queries_window: | |
| self._similar_query_buffer.pop(0) | |
| # Update pattern count | |
| self._query_patterns[normalized] += 1 | |
| def _normalize_query(self, query_sql: str) -> str: | |
| """ | |
| Normalize query by removing parameters. | |
| Converts: SELECT * FROM users WHERE id = 123 | |
| To: SELECT * FROM users WHERE id = ? | |
| """ | |
| import re | |
| # Replace numbers with ? | |
| normalized = re.sub(r"\b\d+\b", "?", query_sql) | |
| # Replace string literals with ? | |
| normalized = re.sub(r"'[^']*'", "?", normalized) | |
| # Replace UUIDs with ? | |
| normalized = re.sub( | |
| r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", | |
| "?", | |
| normalized, | |
| flags=re.IGNORECASE, | |
| ) | |
| return normalized | |
| def _detect_n_plus_1(self) -> list[dict]: | |
| """ | |
| Detect N+1 query patterns in recent queries. | |
| Returns: | |
| List of detected N+1 patterns | |
| """ | |
| patterns = [] | |
| # Count occurrences of normalized queries | |
| query_counts = defaultdict(int) # type: ignore[name-defined, index, return-value, var-annotated] | |
| for query in self._similar_query_buffer: | |
| query_counts[query] += 1 | |
| # Find queries that repeat above threshold | |
| for query, count in query_counts.items(): | |
| if count >= self.n_plus_1_threshold: | |
| patterns.append( | |
| { | |
| "query_pattern": query, | |
| "occurrences": count, | |
| "issue": "N+1 query pattern detected", | |
| "recommendation": "Use eager loading or batch queries", | |
| } | |
| ) | |
| # Update metric | |
| query_type, table = self._parse_query(query) | |
| db_n_plus_1_detected.labels(table=table).inc() | |
| logger.warning( | |
| f"N+1 pattern detected: {count} similar queries", | |
| extra={"query_pattern": query[:200], "occurrences": count}, | |
| ) | |
| return patterns | |
| # ============================================================================= | |
| # Global Profiler Instance | |
| # ============================================================================= | |
| # Global profiler (shared across requests) | |
| _global_profiler = QueryProfiler() | |
| def get_profiler() -> QueryProfiler: | |
| """Get global query profiler instance.""" | |
| return _global_profiler | |
| # ============================================================================= | |
| # SQLAlchemy Event Listeners | |
| # ============================================================================= | |
| def setup_query_profiling(engine: Engine): | |
| """ | |
| Set up SQLAlchemy event listeners for query profiling. | |
| Args: | |
| engine: SQLAlchemy engine instance | |
| """ | |
| profiler = get_profiler() | |
| def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): | |
| """Record query start time.""" | |
| context._query_start_time = time.perf_counter() | |
| def after_cursor_execute(conn, cursor, statement, parameters, context, executemany): | |
| """Record query end time and log.""" | |
| start_time = getattr(context, "_query_start_time", None) | |
| if start_time: | |
| duration_ms = (time.perf_counter() - start_time) * 1000 | |
| profiler.log_query(statement, duration_ms, parameters) | |
| logger.info("✅ Query profiling enabled") | |
| # ============================================================================= | |
| # FastAPI Middleware | |
| # ============================================================================= | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.requests import Request | |
| from starlette.responses import Response | |
| class QueryProfilingMiddleware(BaseHTTPMiddleware): | |
| """ | |
| FastAPI middleware for query profiling. | |
| Tracks queries per request and logs statistics. | |
| """ | |
| async def dispatch(self, request: Request, call_next): | |
| """Process request with query profiling.""" | |
| profiler = get_profiler() | |
| # Start request tracking | |
| profiler.start_request() | |
| # Process request | |
| response = await call_next(request) | |
| # End request tracking | |
| stats = profiler.end_request() | |
| # Add query stats to response headers (optional, for debugging) | |
| response.headers["X-DB-Query-Count"] = str(stats["total_queries"]) | |
| response.headers["X-DB-Query-Time-Ms"] = f"{stats['total_time_ms']:.2f}" | |
| # Log if there are performance issues | |
| if stats["slow_query_count"] > 0 or stats["n_plus_1_patterns"]: | |
| logger.warning( | |
| f"Request to {request.url.path} had {stats['slow_query_count']} slow queries " | |
| f"and {len(stats['n_plus_1_patterns'])} N+1 patterns", | |
| extra={ | |
| "path": request.url.path, | |
| "method": request.method, | |
| "total_queries": stats["total_queries"], | |
| "total_time_ms": stats["total_time_ms"], | |
| "slow_query_count": stats["slow_query_count"], | |
| "n_plus_1_count": len(stats["n_plus_1_patterns"]), | |
| }, | |
| ) | |
| return response | |
| # ============================================================================= | |
| # Context Manager for Manual Profiling | |
| # ============================================================================= | |
| def profile_queries(description: str = ""): | |
| """ | |
| Context manager for profiling queries in a code block. | |
| Usage: | |
| with profile_queries("Load user data"): | |
| users = session.query(User).all() | |
| Args: | |
| description: Description of the code block | |
| """ | |
| profiler = get_profiler() | |
| profiler.start_request() | |
| start_time = time.perf_counter() | |
| try: | |
| yield profiler | |
| finally: | |
| duration_ms = (time.perf_counter() - start_time) * 1000 | |
| stats = profiler.end_request() | |
| logger.info( | |
| f"Query profiling [{description}]: " | |
| f"{stats['total_queries']} queries in {duration_ms:.2f}ms " | |
| f"(DB time: {stats['total_time_ms']:.2f}ms)", | |
| extra={ | |
| "description": description, | |
| "total_queries": stats["total_queries"], | |
| "total_time_ms": stats["total_time_ms"], | |
| "block_duration_ms": duration_ms, | |
| }, | |
| ) | |