Class: CodeToQuery::Performance::Optimizer

Inherits:
Object
  • Object
show all
Defined in:
lib/code_to_query/performance/optimizer.rb

Overview

Query optimization and performance analysis

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Optimizer

Returns a new instance of Optimizer.



9
10
11
12
# File 'lib/code_to_query/performance/optimizer.rb', line 9

def initialize(config)
  @config = config
  @query_stats = {}
end

Instance Method Details

#optimize_query(sql, intent = {}) ⇒ Object

Analyze and optimize a query before execution



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/code_to_query/performance/optimizer.rb', line 15

def optimize_query(sql, intent = {})
  start_time = Time.now

  analysis = analyze_query(sql, intent)
  optimized_sql = apply_optimizations(sql, analysis)

  optimization_time = Time.now - start_time

  {
    original_sql: sql,
    optimized_sql: optimized_sql,
    analysis: analysis,
    optimization_time: optimization_time,
    recommendations: generate_recommendations(analysis)
  }
end

#performance_reportObject

Get performance insights



74
75
76
77
78
79
80
81
82
# File 'lib/code_to_query/performance/optimizer.rb', line 74

def performance_report
  {
    total_queries: @query_stats.size,
    most_frequent: most_frequent_queries,
    slowest: slowest_queries,
    fastest: fastest_queries,
    recommendations: global_recommendations
  }
end

#track_query_performance(sql, execution_time, result_count = 0) ⇒ Object

Performance monitoring for executed queries



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
# File 'lib/code_to_query/performance/optimizer.rb', line 33

def track_query_performance(sql, execution_time, result_count = 0)
  query_hash = Digest::SHA256.hexdigest(sql)

  @query_stats[query_hash] ||= {
    sql: sql,
    execution_count: 0,
    total_time: 0.0,
    min_time: Float::INFINITY,
    max_time: 0.0,
    avg_time: 0.0,
    last_executed: nil,
    result_counts: []
  }

  stats = @query_stats[query_hash]
  prev_count = stats[:execution_count]
  prev_total = stats[:total_time]
  prev_avg = prev_count.positive? ? (prev_total / prev_count) : 0.0

  stats[:execution_count] += 1
  stats[:total_time] += execution_time
  stats[:min_time] = [stats[:min_time], execution_time].min
  stats[:max_time] = [stats[:max_time], execution_time].max
  stats[:avg_time] = stats[:total_time] / stats[:execution_count]
  stats[:last_executed] = Time.now
  stats[:result_counts] << result_count

  # Alert on performance degradation relative to previous average
  if prev_count >= 5 && execution_time > (prev_avg * 3)
    message = '[code_to_query] PERFORMANCE ALERT: Query performance degrading'
    CodeToQuery.config.logger.warn(message)
    warn message
  end

  # Alert on slow queries based on running average and other signals
  check_performance_alerts(stats)

  stats
end