summaryrefslogtreecommitdiff
path: root/lib/peek/views/active_record.rb
blob: 4040bed50a9bb1e2e811420de477837163b55607 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true

module Peek
  module Views
    class ActiveRecord < DetailedView
      DEFAULT_THRESHOLDS = {
        calls: 100,
        duration: 3000,
        individual_call: 1000
      }.freeze

      THRESHOLDS = {
        production: {
          calls: 100,
          duration: 15000,
          individual_call: 5000
        }
      }.freeze

      def self.thresholds
        @thresholds ||= THRESHOLDS.fetch(Rails.env.to_sym, DEFAULT_THRESHOLDS)
      end

      def results
        super.merge(summary: summary)
      end

      private

      def summary
        detail_store.each_with_object({}) do |item, count|
          count_summary(item, count)
        end
      end

      def count_summary(item, count)
        if item[:cached].present?
          count[item[:cached]] ||= 0
          count[item[:cached]] += 1
        end

        if item[:transaction].present?
          count[item[:transaction]] ||= 0
          count[item[:transaction]] += 1
        end
      end

      def setup_subscribers
        super

        subscribe('sql.active_record') do |_, start, finish, _, data|
          detail_store << generate_detail(start, finish, data) if Gitlab::PerformanceBar.enabled_for_request?
        end
      end

      def generate_detail(start, finish, data)
        {
          start: start,
          duration: finish - start,
          sql: data[:sql].strip,
          backtrace: Gitlab::BacktraceCleaner.clean_backtrace(caller),
          cached: data[:cached] ? 'Cached' : '',
          transaction: data[:connection].transaction_open? ? 'In a transaction' : ''
        }
      end
    end
  end
end

Peek::Views::ActiveRecord.prepend_if_ee('EE::Peek::Views::ActiveRecord')