Class: Chronos::Core::SqlQueryAnalyzer

Inherits:
Object
  • Object
show all
Defined in:
lib/chronos/core/sql_query_analyzer.rb

Overview

Derives bounded query-shape evidence and index recommendations from normalized SQL.

Examples:

SqlQueryAnalyzer.new.call("normalized_query" => "SELECT * FROM users WHERE email = ?")

Constant Summary collapse

MAX_TABLES =

rubocop:disable Metrics/ClassLength

8
MAX_COLUMNS =
12
MAX_INDEXES =
20
MAX_DIAGNOSTICS =
20
IDENTIFIER =
"[A-Za-z_][A-Za-z0-9_$]*".freeze
TABLE_PATTERN =
/\b(?:FROM|JOIN)\s+["`\[]?(#{IDENTIFIER}(?:\.#{IDENTIFIER})?)["`\]]?
(?:\s+(?:AS\s+)?(#{IDENTIFIER}))?/ix
CLAUSE_END =
/\b(?:GROUP\s+BY|ORDER\s+BY|HAVING|LIMIT|OFFSET|UNION|RETURNING)\b/i
RESERVED =
%w(WHERE JOIN LEFT RIGHT INNER OUTER FULL CROSS ON GROUP ORDER HAVING LIMIT OFFSET).freeze

Instance Method Summary collapse

Instance Method Details

#call(query, inspection = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/chronos/core/sql_query_analyzer.rb', line 26

def call(query, inspection = {})
  data = hash(query)
  normalized = bounded(data["normalized_query"] || data[:normalized_query], 512)
  operation = (data["operation"] || data[:operation]).to_s.upcase
  return empty_analysis(operation) unless operation == "SELECT" && !normalized.empty?

  aliases = table_aliases(normalized, data["table"] || data[:table])
  access = access_columns(normalized, aliases)
  candidates = index_candidates(access, hash(inspection))
  evidence = inspection_evidence(inspection)
  {
    "operation" => operation,
    "tables" => aliases.values.uniq.first(MAX_TABLES),
    "access_columns" => access,
    "index_candidates" => candidates,
    "inspection" => evidence,
    "diagnostics" => diagnostics(candidates, evidence)
  }
rescue StandardError
  empty_analysis("UNKNOWN")
end