Class: QueryGuard::Analysis::AggregationRiskDetector

Inherits:
RiskDetector
  • Object
show all
Defined in:
lib/query_guard/analysis/risk_detectors.rb

Overview

Detects GROUP BY / DISTINCT patterns

Instance Attribute Summary

Attributes inherited from RiskDetector

#name

Instance Method Summary collapse

Constructor Details

#initialize ⇒ AggregationRiskDetector

Returns a new instance of AggregationRiskDetector.



220
221
222
# File 'lib/query_guard/analysis/risk_detectors.rb', line 220

def initialize
  super(:aggregation_risk)
end

Instance Method Details

#detect(query, config) ⇒ Object



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
# File 'lib/query_guard/analysis/risk_detectors.rb', line 224

def detect(query, config)
  risks = []
  sql = query.sql

  # DISTINCT on large columns
  if query.sql.match?(/\bSELECT\s+DISTINCT\b/i)
    risks << {
      pattern: :distinct_usage,
      risk_level: :low,
      message: "DISTINCT forces sorting; ensure needed and indexed properly",
      metadata: {
        recommendation: "Verify uniqueness constraint or consider GROUP BY",
        impact: "Sorting overhead"
      }
    }
  end

  # GROUP BY without ORDER BY (random order)
  if sql.match?(/\bGROUP\s+BY\b/i) && !sql.match?(/\bORDER\s+BY\b/i)
    risks << {
      pattern: :group_by_unordered,
      risk_level: :low,
      message: "GROUP BY without ORDER BY returns results in random order; add ORDER BY if order matters",
      metadata: {
        recommendation: "Add ORDER BY if result order is important",
        impact: "Unpredictable result ordering"
      }
    }
  end

  risks
end