Spaces:
Paused
Paused
Download shared/query_optimizer.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 33.2 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/query_optimizer.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/query_optimizer.py
-
curl -L -o query_optimizer.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/query_optimizer.py
33.2 kB
| """ | |
| Supabase query optimization and indexing system. | |
| Provides query analysis, optimization suggestions, and automatic indexing. | |
| """ | |
| import asyncio | |
| import logging | |
| import time | |
| import hashlib | |
| from typing import Dict, List, Any, Optional, Tuple, Set | |
| from dataclasses import dataclass | |
| from datetime import datetime, timedelta | |
| from collections import defaultdict, Counter | |
| import re | |
| import json | |
| from .supabase_config import get_supabase_client | |
| from .caching import cache_manager, cached | |
| from .models import UserContext | |
| logger = logging.getLogger(__name__) | |
| class QueryMetrics: | |
| """Query performance metrics.""" | |
| query_hash: str | |
| query_text: str | |
| execution_count: int | |
| total_duration_ms: float | |
| avg_duration_ms: float | |
| max_duration_ms: float | |
| min_duration_ms: float | |
| last_executed: datetime | |
| tables_accessed: List[str] | |
| estimated_rows: Optional[int] = None | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| 'query_hash': self.query_hash, | |
| 'query_text': self.query_text[:200] + '...' if len(self.query_text) > 200 else self.query_text, | |
| 'execution_count': self.execution_count, | |
| 'total_duration_ms': self.total_duration_ms, | |
| 'avg_duration_ms': self.avg_duration_ms, | |
| 'max_duration_ms': self.max_duration_ms, | |
| 'min_duration_ms': self.min_duration_ms, | |
| 'last_executed': self.last_executed.isoformat(), | |
| 'tables_accessed': self.tables_accessed, | |
| 'estimated_rows': self.estimated_rows | |
| } | |
| class IndexRecommendation: | |
| """Index recommendation.""" | |
| table_name: str | |
| columns: List[str] | |
| index_type: str # 'btree', 'hash', 'gin', 'gist' | |
| reason: str | |
| estimated_benefit: str # 'high', 'medium', 'low' | |
| query_patterns: List[str] | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| 'table_name': self.table_name, | |
| 'columns': self.columns, | |
| 'index_type': self.index_type, | |
| 'reason': self.reason, | |
| 'estimated_benefit': self.estimated_benefit, | |
| 'query_patterns': self.query_patterns | |
| } | |
| class QueryOptimizationSuggestion: | |
| """Query optimization suggestion.""" | |
| original_query: str | |
| optimized_query: str | |
| optimization_type: str | |
| estimated_improvement: str | |
| explanation: str | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| 'original_query': self.original_query[:200] + '...' if len(self.original_query) > 200 else self.original_query, | |
| 'optimized_query': self.optimized_query[:200] + '...' if len(self.optimized_query) > 200 else self.optimized_query, | |
| 'optimization_type': self.optimization_type, | |
| 'estimated_improvement': self.estimated_improvement, | |
| 'explanation': self.explanation | |
| } | |
| class QueryAnalyzer: | |
| """Analyzes SQL queries for optimization opportunities.""" | |
| def __init__(self): | |
| self.query_patterns = { | |
| 'select_all': re.compile(r'SELECT\s+\*\s+FROM', re.IGNORECASE), | |
| 'no_where': re.compile(r'SELECT.*FROM\s+(\w+)(?!\s+WHERE)', re.IGNORECASE | re.DOTALL), | |
| 'no_limit': re.compile(r'SELECT.*FROM.*(?!LIMIT)', re.IGNORECASE | re.DOTALL), | |
| 'like_prefix': re.compile(r"LIKE\s+'([^%].*%)'", re.IGNORECASE), | |
| 'like_suffix': re.compile(r"LIKE\s+'(%.*[^%])'", re.IGNORECASE), | |
| 'like_contains': re.compile(r"LIKE\s+'(%.*%)'", re.IGNORECASE), | |
| 'order_by': re.compile(r'ORDER\s+BY\s+([\w\s,]+)', re.IGNORECASE), | |
| 'group_by': re.compile(r'GROUP\s+BY\s+([\w\s,]+)', re.IGNORECASE), | |
| 'join': re.compile(r'JOIN\s+(\w+)\s+ON\s+([\w\s.=]+)', re.IGNORECASE), | |
| 'where_conditions': re.compile(r'WHERE\s+(.*?)(?:\s+ORDER|\s+GROUP|\s+LIMIT|$)', re.IGNORECASE | re.DOTALL) | |
| } | |
| def analyze_query(self, query: str) -> Dict[str, Any]: | |
| """Analyze a query for optimization opportunities.""" | |
| analysis = { | |
| 'query_hash': hashlib.md5(query.encode()).hexdigest(), | |
| 'tables': self._extract_tables(query), | |
| 'columns': self._extract_columns(query), | |
| 'has_where': 'WHERE' in query.upper(), | |
| 'has_limit': 'LIMIT' in query.upper(), | |
| 'has_order_by': 'ORDER BY' in query.upper(), | |
| 'has_group_by': 'GROUP BY' in query.upper(), | |
| 'has_joins': 'JOIN' in query.upper(), | |
| 'select_all': bool(self.query_patterns['select_all'].search(query)), | |
| 'like_patterns': self._analyze_like_patterns(query), | |
| 'potential_issues': [], | |
| 'optimization_opportunities': [] | |
| } | |
| # Identify potential issues | |
| if analysis['select_all']: | |
| analysis['potential_issues'].append('Uses SELECT * which may fetch unnecessary columns') | |
| if not analysis['has_where'] and not analysis['has_limit']: | |
| analysis['potential_issues'].append('No WHERE clause or LIMIT - may scan entire table') | |
| if not analysis['has_limit'] and not analysis['has_group_by']: | |
| analysis['potential_issues'].append('No LIMIT clause - may return excessive rows') | |
| # Identify optimization opportunities | |
| if analysis['like_patterns']['contains']: | |
| analysis['optimization_opportunities'].append('LIKE %pattern% queries could benefit from full-text search') | |
| if analysis['has_order_by'] and not analysis['has_limit']: | |
| analysis['optimization_opportunities'].append('ORDER BY without LIMIT may be inefficient') | |
| return analysis | |
| def _extract_tables(self, query: str) -> List[str]: | |
| """Extract table names from query.""" | |
| tables = [] | |
| # FROM clause | |
| from_match = re.search(r'FROM\s+(\w+)', query, re.IGNORECASE) | |
| if from_match: | |
| tables.append(from_match.group(1)) | |
| # JOIN clauses | |
| join_matches = re.findall(r'JOIN\s+(\w+)', query, re.IGNORECASE) | |
| tables.extend(join_matches) | |
| return list(set(tables)) | |
| def _extract_columns(self, query: str) -> List[str]: | |
| """Extract column names from query.""" | |
| columns = [] | |
| # WHERE conditions | |
| where_match = self.query_patterns['where_conditions'].search(query) | |
| if where_match: | |
| where_clause = where_match.group(1) | |
| # Simple column extraction (could be more sophisticated) | |
| column_matches = re.findall(r'(\w+)\s*[=<>!]', where_clause) | |
| columns.extend(column_matches) | |
| # ORDER BY | |
| order_match = self.query_patterns['order_by'].search(query) | |
| if order_match: | |
| order_columns = [col.strip() for col in order_match.group(1).split(',')] | |
| columns.extend(order_columns) | |
| # GROUP BY | |
| group_match = self.query_patterns['group_by'].search(query) | |
| if group_match: | |
| group_columns = [col.strip() for col in group_match.group(1).split(',')] | |
| columns.extend(group_columns) | |
| return list(set(columns)) | |
| def _analyze_like_patterns(self, query: str) -> Dict[str, List[str]]: | |
| """Analyze LIKE patterns in query.""" | |
| return { | |
| 'prefix': self.query_patterns['like_prefix'].findall(query), | |
| 'suffix': self.query_patterns['like_suffix'].findall(query), | |
| 'contains': self.query_patterns['like_contains'].findall(query) | |
| } | |
| class QueryOptimizer: | |
| """Provides query optimization suggestions.""" | |
| def __init__(self): | |
| self.analyzer = QueryAnalyzer() | |
| self.query_metrics: Dict[str, QueryMetrics] = {} | |
| self.optimization_rules = [ | |
| self._optimize_select_star, | |
| self._optimize_missing_where, | |
| self._optimize_missing_limit, | |
| self._optimize_like_patterns, | |
| self._optimize_order_by, | |
| self._optimize_joins | |
| ] | |
| def record_query_execution(self, query: str, duration_ms: float, tables: List[str] = None, estimated_rows: int = None): | |
| """Record query execution metrics.""" | |
| query_hash = hashlib.md5(query.encode()).hexdigest() | |
| if query_hash in self.query_metrics: | |
| metrics = self.query_metrics[query_hash] | |
| metrics.execution_count += 1 | |
| metrics.total_duration_ms += duration_ms | |
| metrics.avg_duration_ms = metrics.total_duration_ms / metrics.execution_count | |
| metrics.max_duration_ms = max(metrics.max_duration_ms, duration_ms) | |
| metrics.min_duration_ms = min(metrics.min_duration_ms, duration_ms) | |
| metrics.last_executed = datetime.utcnow() | |
| if estimated_rows: | |
| metrics.estimated_rows = estimated_rows | |
| else: | |
| analysis = self.analyzer.analyze_query(query) | |
| self.query_metrics[query_hash] = QueryMetrics( | |
| query_hash=query_hash, | |
| query_text=query, | |
| execution_count=1, | |
| total_duration_ms=duration_ms, | |
| avg_duration_ms=duration_ms, | |
| max_duration_ms=duration_ms, | |
| min_duration_ms=duration_ms, | |
| last_executed=datetime.utcnow(), | |
| tables_accessed=tables or analysis['tables'], | |
| estimated_rows=estimated_rows | |
| ) | |
| def get_optimization_suggestions(self, query: str) -> List[QueryOptimizationSuggestion]: | |
| """Get optimization suggestions for a query.""" | |
| suggestions = [] | |
| for rule in self.optimization_rules: | |
| suggestion = rule(query) | |
| if suggestion: | |
| suggestions.append(suggestion) | |
| return suggestions | |
| def _optimize_select_star(self, query: str) -> Optional[QueryOptimizationSuggestion]: | |
| """Suggest replacing SELECT * with specific columns.""" | |
| if re.search(r'SELECT\s+\*', query, re.IGNORECASE): | |
| return QueryOptimizationSuggestion( | |
| original_query=query, | |
| optimized_query=query.replace('*', 'column1, column2, column3'), | |
| optimization_type='select_columns', | |
| estimated_improvement='medium', | |
| explanation='Replace SELECT * with specific columns to reduce data transfer and improve performance' | |
| ) | |
| return None | |
| def _optimize_missing_where(self, query: str) -> Optional[QueryOptimizationSuggestion]: | |
| """Suggest adding WHERE clause for table scans.""" | |
| if 'WHERE' not in query.upper() and 'SELECT' in query.upper(): | |
| table_match = re.search(r'FROM\s+(\w+)', query, re.IGNORECASE) | |
| if table_match: | |
| table_name = table_match.group(1) | |
| optimized = query.rstrip(';') + f" WHERE {table_name}.created_at >= NOW() - INTERVAL '30 days'" | |
| return QueryOptimizationSuggestion( | |
| original_query=query, | |
| optimized_query=optimized, | |
| optimization_type='add_where_clause', | |
| estimated_improvement='high', | |
| explanation='Add WHERE clause to avoid full table scan and limit result set' | |
| ) | |
| return None | |
| def _optimize_missing_limit(self, query: str) -> Optional[QueryOptimizationSuggestion]: | |
| """Suggest adding LIMIT clause.""" | |
| if 'LIMIT' not in query.upper() and 'SELECT' in query.upper() and 'COUNT' not in query.upper(): | |
| optimized = query.rstrip(';') + ' LIMIT 1000' | |
| return QueryOptimizationSuggestion( | |
| original_query=query, | |
| optimized_query=optimized, | |
| optimization_type='add_limit', | |
| estimated_improvement='medium', | |
| explanation='Add LIMIT clause to prevent returning excessive rows' | |
| ) | |
| return None | |
| def _optimize_like_patterns(self, query: str) -> Optional[QueryOptimizationSuggestion]: | |
| """Suggest optimizing LIKE patterns.""" | |
| like_contains = re.search(r"LIKE\s+'%(.*)%'", query, re.IGNORECASE) | |
| if like_contains: | |
| pattern = like_contains.group(1) | |
| column_match = re.search(r'(\w+)\s+LIKE', query, re.IGNORECASE) | |
| if column_match: | |
| column = column_match.group(1) | |
| optimized = re.sub( | |
| r'(\w+)\s+LIKE\s+\'%.*%\'', | |
| f"to_tsvector('english', {column}) @@ plainto_tsquery('english', '{pattern}')", | |
| query, | |
| flags=re.IGNORECASE | |
| ) | |
| return QueryOptimizationSuggestion( | |
| original_query=query, | |
| optimized_query=optimized, | |
| optimization_type='fulltext_search', | |
| estimated_improvement='high', | |
| explanation='Replace LIKE %pattern% with full-text search for better performance' | |
| ) | |
| return None | |
| def _optimize_order_by(self, query: str) -> Optional[QueryOptimizationSuggestion]: | |
| """Suggest ORDER BY optimizations.""" | |
| if 'ORDER BY' in query.upper() and 'LIMIT' not in query.upper(): | |
| optimized = query.rstrip(';') + ' LIMIT 100' | |
| return QueryOptimizationSuggestion( | |
| original_query=query, | |
| optimized_query=optimized, | |
| optimization_type='limit_ordered_results', | |
| estimated_improvement='medium', | |
| explanation='Add LIMIT to ORDER BY queries to improve performance' | |
| ) | |
| return None | |
| def _optimize_joins(self, query: str) -> Optional[QueryOptimizationSuggestion]: | |
| """Suggest JOIN optimizations.""" | |
| # This is a simplified example | |
| if 'JOIN' in query.upper() and 'WHERE' not in query.upper(): | |
| return QueryOptimizationSuggestion( | |
| original_query=query, | |
| optimized_query=query + ' WHERE condition_on_joined_table = value', | |
| optimization_type='filter_joins', | |
| estimated_improvement='medium', | |
| explanation='Add WHERE conditions to filter JOIN results early' | |
| ) | |
| return None | |
| def get_slow_queries(self, threshold_ms: float = 1000) -> List[QueryMetrics]: | |
| """Get queries that exceed performance threshold.""" | |
| return [ | |
| metrics for metrics in self.query_metrics.values() | |
| if metrics.avg_duration_ms > threshold_ms | |
| ] | |
| def get_frequent_queries(self, min_executions: int = 10) -> List[QueryMetrics]: | |
| """Get frequently executed queries.""" | |
| return [ | |
| metrics for metrics in self.query_metrics.values() | |
| if metrics.execution_count >= min_executions | |
| ] | |
| class IndexRecommendationEngine: | |
| """Generates index recommendations based on query patterns.""" | |
| def __init__(self, query_optimizer: QueryOptimizer): | |
| self.query_optimizer = query_optimizer | |
| self.existing_indexes: Dict[str, List[Dict[str, Any]]] = {} | |
| async def analyze_and_recommend_indexes(self) -> List[IndexRecommendation]: | |
| """Analyze query patterns and recommend indexes.""" | |
| recommendations = [] | |
| # Analyze frequent and slow queries | |
| frequent_queries = self.query_optimizer.get_frequent_queries(min_executions=5) | |
| slow_queries = self.query_optimizer.get_slow_queries(threshold_ms=500) | |
| # Combine and deduplicate | |
| all_queries = {q.query_hash: q for q in frequent_queries + slow_queries} | |
| # Analyze each query for index opportunities | |
| for metrics in all_queries.values(): | |
| query_recommendations = await self._analyze_query_for_indexes(metrics) | |
| recommendations.extend(query_recommendations) | |
| # Deduplicate and prioritize recommendations | |
| return self._deduplicate_and_prioritize(recommendations) | |
| async def _analyze_query_for_indexes(self, metrics: QueryMetrics) -> List[IndexRecommendation]: | |
| """Analyze a single query for index opportunities.""" | |
| recommendations = [] | |
| analysis = self.query_optimizer.analyzer.analyze_query(metrics.query_text) | |
| for table in metrics.tables_accessed: | |
| # WHERE clause indexes | |
| if analysis['has_where']: | |
| where_columns = self._extract_where_columns(metrics.query_text, table) | |
| if where_columns: | |
| recommendations.append(IndexRecommendation( | |
| table_name=table, | |
| columns=where_columns, | |
| index_type='btree', | |
| reason='Frequent WHERE clause filtering', | |
| estimated_benefit='high' if metrics.avg_duration_ms > 1000 else 'medium', | |
| query_patterns=[metrics.query_text[:100]] | |
| )) | |
| # ORDER BY indexes | |
| if analysis['has_order_by']: | |
| order_columns = self._extract_order_by_columns(metrics.query_text) | |
| if order_columns: | |
| recommendations.append(IndexRecommendation( | |
| table_name=table, | |
| columns=order_columns, | |
| index_type='btree', | |
| reason='Frequent ORDER BY operations', | |
| estimated_benefit='medium', | |
| query_patterns=[metrics.query_text[:100]] | |
| )) | |
| # Full-text search indexes | |
| if analysis['like_patterns']['contains']: | |
| text_columns = self._extract_text_search_columns(metrics.query_text, table) | |
| if text_columns: | |
| recommendations.append(IndexRecommendation( | |
| table_name=table, | |
| columns=text_columns, | |
| index_type='gin', | |
| reason='Text search patterns detected', | |
| estimated_benefit='high', | |
| query_patterns=[metrics.query_text[:100]] | |
| )) | |
| return recommendations | |
| def _extract_where_columns(self, query: str, table: str) -> List[str]: | |
| """Extract columns used in WHERE clauses for a specific table.""" | |
| columns = [] | |
| where_match = re.search(r'WHERE\s+(.*?)(?:\s+ORDER|\s+GROUP|\s+LIMIT|$)', query, re.IGNORECASE | re.DOTALL) | |
| if where_match: | |
| where_clause = where_match.group(1) | |
| # Look for table.column or just column patterns | |
| patterns = [ | |
| rf'{table}\.(\w+)\s*[=<>!]', | |
| r'(\w+)\s*[=<>!]' | |
| ] | |
| for pattern in patterns: | |
| matches = re.findall(pattern, where_clause, re.IGNORECASE) | |
| columns.extend(matches) | |
| return list(set(columns)) | |
| def _extract_order_by_columns(self, query: str) -> List[str]: | |
| """Extract columns used in ORDER BY clauses.""" | |
| order_match = re.search(r'ORDER\s+BY\s+([\w\s,\.]+)', query, re.IGNORECASE) | |
| if order_match: | |
| order_clause = order_match.group(1) | |
| # Remove ASC/DESC and extract column names | |
| columns = [] | |
| for col in order_clause.split(','): | |
| col = col.strip() | |
| col = re.sub(r'\s+(ASC|DESC)$', '', col, flags=re.IGNORECASE) | |
| col = col.split('.')[-1] # Remove table prefix if present | |
| columns.append(col) | |
| return columns | |
| return [] | |
| def _extract_text_search_columns(self, query: str, table: str) -> List[str]: | |
| """Extract columns used in text search patterns.""" | |
| columns = [] | |
| like_matches = re.findall(rf'({table}\.)?(\w+)\s+LIKE\s+\'%.*%\'', query, re.IGNORECASE) | |
| for match in like_matches: | |
| columns.append(match[1]) | |
| return list(set(columns)) | |
| def _deduplicate_and_prioritize(self, recommendations: List[IndexRecommendation]) -> List[IndexRecommendation]: | |
| """Deduplicate and prioritize index recommendations.""" | |
| # Group by table and columns | |
| grouped = defaultdict(list) | |
| for rec in recommendations: | |
| key = (rec.table_name, tuple(sorted(rec.columns)), rec.index_type) | |
| grouped[key].append(rec) | |
| # Merge grouped recommendations | |
| merged = [] | |
| for (table, columns, index_type), recs in grouped.items(): | |
| # Combine reasons and query patterns | |
| reasons = list(set(rec.reason for rec in recs)) | |
| query_patterns = [] | |
| for rec in recs: | |
| query_patterns.extend(rec.query_patterns) | |
| # Determine benefit level | |
| benefit_scores = {'high': 3, 'medium': 2, 'low': 1} | |
| max_benefit = max(rec.estimated_benefit for rec in recs) | |
| merged.append(IndexRecommendation( | |
| table_name=table, | |
| columns=list(columns), | |
| index_type=index_type, | |
| reason='; '.join(reasons), | |
| estimated_benefit=max_benefit, | |
| query_patterns=list(set(query_patterns)) | |
| )) | |
| # Sort by estimated benefit | |
| benefit_order = {'high': 0, 'medium': 1, 'low': 2} | |
| merged.sort(key=lambda x: benefit_order[x.estimated_benefit]) | |
| return merged | |
| class SupabaseQueryOptimizer: | |
| """Main class for Supabase query optimization.""" | |
| def __init__(self): | |
| self.query_optimizer = QueryOptimizer() | |
| self.index_engine = IndexRecommendationEngine(self.query_optimizer) | |
| self._monitoring_enabled = True | |
| async def execute_optimized_query(self, query: str, params: Tuple = None, user_context: UserContext = None) -> Any: | |
| """Execute query with optimization monitoring.""" | |
| start_time = time.time() | |
| try: | |
| # Check cache first | |
| cached_result = cache_manager.get_query_result(query, params, user_context.user_id if user_context else None) | |
| if cached_result is not None: | |
| return cached_result | |
| # Execute query | |
| client = await get_supabase_client(use_service_role=True) | |
| # For Supabase, we'll use the table() method for most queries | |
| # This is a simplified implementation | |
| result = await asyncio.to_thread( | |
| client.rpc, 'execute_sql', {'sql': query, 'params': params or []} | |
| ) | |
| # Record metrics | |
| duration_ms = (time.time() - start_time) * 1000 | |
| if self._monitoring_enabled: | |
| tables = self.query_optimizer.analyzer._extract_tables(query) | |
| self.query_optimizer.record_query_execution(query, duration_ms, tables) | |
| # Cache result | |
| cache_manager.set_query_result( | |
| query, result, params, | |
| user_context.user_id if user_context else None, | |
| ttl=300 # 5 minutes | |
| ) | |
| return result | |
| except Exception as e: | |
| duration_ms = (time.time() - start_time) * 1000 | |
| logger.error(f"Query execution failed after {duration_ms}ms: {e}") | |
| raise | |
| async def get_query_statistics(self) -> Dict[str, Any]: | |
| """Get comprehensive query statistics.""" | |
| all_metrics = list(self.query_optimizer.query_metrics.values()) | |
| if not all_metrics: | |
| return { | |
| 'total_queries': 0, | |
| 'avg_duration_ms': 0, | |
| 'slow_queries': [], | |
| 'frequent_queries': [], | |
| 'table_access_patterns': {} | |
| } | |
| total_executions = sum(m.execution_count for m in all_metrics) | |
| total_duration = sum(m.total_duration_ms for m in all_metrics) | |
| # Table access patterns | |
| table_access = defaultdict(int) | |
| for metrics in all_metrics: | |
| for table in metrics.tables_accessed: | |
| table_access[table] += metrics.execution_count | |
| return { | |
| 'total_queries': len(all_metrics), | |
| 'total_executions': total_executions, | |
| 'avg_duration_ms': total_duration / total_executions if total_executions > 0 else 0, | |
| 'slow_queries': [m.to_dict() for m in self.query_optimizer.get_slow_queries()], | |
| 'frequent_queries': [m.to_dict() for m in self.query_optimizer.get_frequent_queries()], | |
| 'table_access_patterns': dict(table_access), | |
| 'optimization_opportunities': len([ | |
| m for m in all_metrics | |
| if self.query_optimizer.get_optimization_suggestions(m.query_text) | |
| ]) | |
| } | |
| async def get_index_recommendations(self) -> List[Dict[str, Any]]: | |
| """Get index recommendations.""" | |
| recommendations = await self.index_engine.analyze_and_recommend_indexes() | |
| return [rec.to_dict() for rec in recommendations] | |
| async def get_optimization_report(self) -> Dict[str, Any]: | |
| """Get comprehensive optimization report.""" | |
| stats = await self.get_query_statistics() | |
| recommendations = await self.get_index_recommendations() | |
| # Get optimization suggestions for slow queries | |
| optimization_suggestions = [] | |
| for metrics in self.query_optimizer.get_slow_queries(): | |
| suggestions = self.query_optimizer.get_optimization_suggestions(metrics.query_text) | |
| for suggestion in suggestions: | |
| optimization_suggestions.append({ | |
| 'query_hash': metrics.query_hash, | |
| 'suggestion': suggestion.to_dict() | |
| }) | |
| return { | |
| 'timestamp': datetime.utcnow().isoformat(), | |
| 'query_statistics': stats, | |
| 'index_recommendations': recommendations, | |
| 'optimization_suggestions': optimization_suggestions, | |
| 'cache_statistics': cache_manager.get_comprehensive_stats(), | |
| 'performance_insights': await self._generate_performance_insights() | |
| } | |
| async def _generate_performance_insights(self) -> Dict[str, Any]: | |
| """Generate performance insights and recommendations.""" | |
| all_metrics = list(self.query_optimizer.query_metrics.values()) | |
| if not all_metrics: | |
| return {'insights': [], 'recommendations': []} | |
| insights = [] | |
| recommendations = [] | |
| # Analyze query patterns | |
| slow_query_count = len(self.query_optimizer.get_slow_queries()) | |
| total_queries = len(all_metrics) | |
| if slow_query_count > total_queries * 0.2: # More than 20% slow queries | |
| insights.append(f"High percentage of slow queries: {slow_query_count}/{total_queries} ({slow_query_count/total_queries*100:.1f}%)") | |
| recommendations.append("Review and optimize frequently used queries") | |
| # Analyze table access patterns | |
| table_access = defaultdict(int) | |
| for metrics in all_metrics: | |
| for table in metrics.tables_accessed: | |
| table_access[table] += metrics.execution_count | |
| if table_access: | |
| most_accessed_table = max(table_access.items(), key=lambda x: x[1]) | |
| insights.append(f"Most accessed table: {most_accessed_table[0]} ({most_accessed_table[1]} accesses)") | |
| if most_accessed_table[1] > 100: | |
| recommendations.append(f"Consider optimizing queries for table '{most_accessed_table[0]}'") | |
| recommendations.append(f"Review indexing strategy for table '{most_accessed_table[0]}'") | |
| # Analyze query complexity | |
| complex_queries = [m for m in all_metrics if len(m.query_text) > 500 or 'JOIN' in m.query_text.upper()] | |
| if len(complex_queries) > total_queries * 0.3: | |
| insights.append(f"High number of complex queries: {len(complex_queries)}/{total_queries}") | |
| recommendations.append("Consider breaking down complex queries into simpler ones") | |
| recommendations.append("Review query structure and eliminate unnecessary JOINs") | |
| # Cache hit rate analysis | |
| cache_stats = cache_manager.get_comprehensive_stats() | |
| if 'query_cache' in cache_stats: | |
| query_cache_stats = cache_stats['query_cache'] | |
| if query_cache_stats.get('hit_rate', 0) < 0.5: | |
| insights.append(f"Low query cache hit rate: {query_cache_stats.get('hit_rate', 0)*100:.1f}%") | |
| recommendations.append("Review query caching strategy and TTL settings") | |
| recommendations.append("Consider parameterizing similar queries for better cache utilization") | |
| return { | |
| 'insights': insights, | |
| 'recommendations': recommendations, | |
| 'metrics_summary': { | |
| 'total_queries': total_queries, | |
| 'slow_queries': slow_query_count, | |
| 'complex_queries': len(complex_queries), | |
| 'most_accessed_tables': dict(sorted(table_access.items(), key=lambda x: x[1], reverse=True)[:5]) | |
| } | |
| } | |
| async def auto_optimize_queries(self, dry_run: bool = True) -> Dict[str, Any]: | |
| """Automatically apply safe query optimizations.""" | |
| optimization_results = { | |
| 'optimizations_applied': [], | |
| 'optimizations_suggested': [], | |
| 'errors': [] | |
| } | |
| try: | |
| # Get slow queries for optimization | |
| slow_queries = self.query_optimizer.get_slow_queries(threshold_ms=2000) # 2 second threshold | |
| for metrics in slow_queries[:10]: # Limit to top 10 slow queries | |
| try: | |
| suggestions = self.query_optimizer.get_optimization_suggestions(metrics.query_text) | |
| for suggestion in suggestions: | |
| if suggestion.optimization_type in ['add_limit', 'select_columns']: | |
| # These are safe optimizations | |
| if not dry_run: | |
| # In a real implementation, we would apply the optimization | |
| # For now, we just record what would be done | |
| optimization_results['optimizations_applied'].append({ | |
| 'query_hash': metrics.query_hash, | |
| 'optimization': suggestion.to_dict(), | |
| 'estimated_improvement': suggestion.estimated_improvement | |
| }) | |
| else: | |
| optimization_results['optimizations_suggested'].append({ | |
| 'query_hash': metrics.query_hash, | |
| 'optimization': suggestion.to_dict(), | |
| 'estimated_improvement': suggestion.estimated_improvement | |
| }) | |
| else: | |
| # More complex optimizations require manual review | |
| optimization_results['optimizations_suggested'].append({ | |
| 'query_hash': metrics.query_hash, | |
| 'optimization': suggestion.to_dict(), | |
| 'requires_manual_review': True | |
| }) | |
| except Exception as e: | |
| optimization_results['errors'].append({ | |
| 'query_hash': metrics.query_hash, | |
| 'error': str(e) | |
| }) | |
| except Exception as e: | |
| optimization_results['errors'].append({ | |
| 'general_error': str(e) | |
| }) | |
| return optimization_results | |
| # Global optimizer instance | |
| supabase_optimizer = SupabaseQueryOptimizer() |