Class: SqlGenius::Core::Ai::PatternGrouper

Inherits:
Object
  • Object
show all
Defined in:
lib/sql_genius/core/ai/pattern_grouper.rb

Overview

Groups slow queries by shared root cause so a single fix can improve multiple queries at once. Pulls high-cost statements from performance_schema, extracts referenced tables, builds schema context, and asks the LLM to cluster queries by underlying issue.

Construct with:

connection - a Core::Connection implementation
client     - a Core::Ai::Client
config     - the Core::Ai::Config

Call:

.call() -> Hash with "groups" key containing markdown analysis

Constant Summary collapse

QUERY_LIMIT =
30
ROWS_RATIO_THRESHOLD =
10
AVG_TIME_THRESHOLD =
50

Instance Method Summary collapse

Constructor Details

#initialize(connection, client, config) ⇒ PatternGrouper

Returns a new instance of PatternGrouper.



23
24
25
26
27
# File 'lib/sql_genius/core/ai/pattern_grouper.rb', line 23

def initialize(connection, client, config)
  @connection = connection
  @client = client
  @config = config
end

Instance Method Details

#callObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/sql_genius/core/ai/pattern_grouper.rb', line 29

def call
  all_stats = Analysis::QueryStats.new(@connection).call(sort: "total_time", limit: QUERY_LIMIT)
  high_cost = all_stats.select { |s| s[:rows_ratio] > ROWS_RATIO_THRESHOLD || s[:avg_time_ms] > AVG_TIME_THRESHOLD }
  return { "groups" => "No high-cost queries found to analyze." } if high_cost.empty?

  tables = extract_tables(high_cost)
  schema = tables.any? ? SchemaContextBuilder.new(@connection).call(tables, detail: :basic) : ""

  messages = [
    { role: "system", content: system_prompt },
    { role: "user",   content: user_prompt(high_cost, schema) },
  ]

  @client.chat(messages: messages)
end