Sha256: 72972153d87e0d95c3131955b15d0c483b3b720d5133bb5245107e996bd3dd65

Contents?: true

Size: 1.2 KB

Versions: 10

Compression:

Stored size: 1.2 KB

Contents

require "nsa/statsd/publisher"

module NSA
  module Collectors
    module ActiveRecord
      extend ::NSA::Statsd::Publisher

      # Ordered by most common query type
      MATCHERS = [
        [ :select, /^\s*SELECT.+?FROM\s+"?([^".\s),]+)"?/im ],
        [ :insert, /^\s*INSERT INTO\s+"?([^".\s]+)"?/im ],
        [ :update, /^\s*UPDATE\s+"?([^".\s]+)"?/im ],
        [ :delete, /^\s*DELETE.+FROM\s+"?([^".\s]+)"?/im ]
      ].freeze

      EMPTY_MATCH_RESULT = []

      def self.collect(key_prefix)
        ::ActiveSupport::Notifications.subscribe("sql.active_record") do |_, start, finish, _id, payload|
          query_type, table_name = match_query(payload[:sql])
          unless query_type.nil?
            stat_name = "#{key_prefix}.tables.#{table_name}.queries.#{query_type}.duration"
            duration_ms = (finish - start) * 1000
            statsd_timing(stat_name, duration_ms)
          end
        end
      end

      def self.match_query(sql)
        MATCHERS
          .lazy
          .map { |(type, regex)|
            match = (sql.match(regex) || EMPTY_MATCH_RESULT)
            [ type, match[1] ]
          }
          .detect { |(_, table_name)| ! table_name.nil? }
      end

    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
nsa-0.3.0 lib/nsa/collectors/active_record.rb
nsa-0.2.8 lib/nsa/collectors/active_record.rb
nsa-0.2.7 lib/nsa/collectors/active_record.rb
nsa-0.2.5 lib/nsa/collectors/active_record.rb
nsa-0.2.4 lib/nsa/collectors/active_record.rb
nsa-0.2.3 lib/nsa/collectors/active_record.rb
nsa-0.2.1 lib/nsa/collectors/active_record.rb
nsa-0.2.0 lib/nsa/collectors/active_record.rb
nsa-0.1.4 lib/nsa/collectors/active_record.rb
nsa-0.1.3 lib/nsa/collectors/active_record.rb