File size: 33,175 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
"""

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__)


@dataclass
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
        }


@dataclass
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
        }


@dataclass
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
    
    @cached(ttl=3600, key_prefix="query_stats")
    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()