Class: PgCanary::Rules::DistinctWithJoin

Inherits:
Base
  • Object
show all
Defined in:
lib/pg_canary/rules/definitions/distinct_with_join.rb

Overview

Tier 2 (opt-in): DISTINCT combined with JOIN. Frequently the DISTINCT only exists to undo row fanout caused by the join — the work of producing and then deduplicating the duplicates is wasted. Legitimate uses exist, hence opt-in.

Constant Summary

Constants included from PgQuerySupport

PgQuerySupport::COMPARISON_OPS

Instance Method Summary collapse

Methods inherited from Base

all, #enabled?, options, rule_name

Instance Method Details

#check(query) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pg_canary/rules/definitions/distinct_with_join.rb', line 14

def check(query)
  detections = []
  query.each_scope do |scope|
    next unless scope.stmt.distinct_clause.any?
    next unless joined?(scope)

    detections << detection(
      query,
      table: scope.tables.first,
      message: "DISTINCT combined with JOIN often hides row fanout from the join: duplicate rows " \
               "are produced and then sorted/hashed away.",
      suggestion: "If DISTINCT only compensates for join duplication, rewrite the join as a " \
                  "semi-join: WHERE EXISTS (SELECT 1 FROM joined WHERE joined.ref_id = t.id)."
    )
  end
  detections
end

#default_enabledObject



10
11
12
# File 'lib/pg_canary/rules/definitions/distinct_with_join.rb', line 10

def default_enabled
  false
end