Sha256: 8ac133820a10766ae1ce586c6a30a933caeff981b709e1f5affb5bf2e3b406f4

Contents?: true

Size: 1.9 KB

Versions: 1

Compression:

Stored size: 1.9 KB

Contents

# frozen_string_literal: true

require 'json'
require 'active_support/configurable'
require 'active_support/log_subscriber'
require 'active_record'
require 'active_record/log_subscriber'

module ActiveRecord
  class ModSqlLogSubscriber < ::ActiveRecord::LogSubscriber
    include ActiveSupport::Configurable

    VERSION = "0.0.1"

    config_accessor :disable, :log_level, :log_format, :target_statements

    # Default values
    self.disable = false
    self.log_level = :info
    self.log_format = :text
    self.target_statements = %w(insert update delete truncate begin commit rollback savepoint release\ savepoint)

    def sql(event)
      return if self.disable

      payload = event.payload
      sql = payload[:sql]

      return if sql.nil?
      return if payload[:cached]
      return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])
      return unless target_sql_checker.match?(sql)

      binds = extract_binds(payload)
      send(self.log_level, formatter.call(sql, binds))
    end

    private

    def target_sql_checker
      @target_sql_checker ||= /\A\s*(#{self.target_statements.join('|')})/mi
    end

    def extract_binds(payload)
      binds = {}
      unless (payload[:binds] || []).empty?
        casted_params = type_casted_binds(payload[:type_casted_binds])
        payload[:binds].zip(casted_params).map do |attr, value|
          key, val = render_bind(attr, value)
          binds[key] = val
        end
      end
      binds
    end

    def formatter
      @formatter ||=
        case self.log_format
        when :text
          ->(sql, binds) { binds.empty? ? sql : "#{sql}  #{binds.inspect}" }
        when :json
          -> (sql, binds) { ::JSON.generate(sql: sql, binds: binds) }
        when :hash
          -> (sql, binds) { { sql: sql, binds: binds } }
        when ::Proc
          self.log_format
        else
          raise "Unexpected log format: #{self.log_format}"
        end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_record-mod_sql_log_subscriber-0.0.1 lib/active_record/mod_sql_log_subscriber.rb