Sha256: 5d702016a1b68453c2b3a9c637b2ec70cae82f68f2f196b52f143da649083e7d

Contents?: true

Size: 1.91 KB

Versions: 1

Compression:

Stored size: 1.91 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.1.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.1.1 lib/active_record/mod_sql_log_subscriber.rb