Class: PgCanary::Rules::DistinctWithJoin

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

Overview

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.

Instance Method Summary collapse

Methods inherited from Base

all, check, default_enabled, enabled?, #initialize, option, options, rule_name

Constructor Details

This class inherits a constructor from PgCanary::Rules::Base

Instance Method Details

#checkObject



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

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

    detections << detection(
      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