Class: SqlTagger

Inherits:
Object
  • Object
show all
Defined in:
lib/sql_tagger.rb

Overview

Instances of this class insert stack trace comments into SQL queries.

Defined Under Namespace

Modules: Initializer, ModuleMethods, Mysql, Mysql2, PG

Constant Summary collapse

VERSION =

Version string

IO.read(
  File.join(File.dirname(__FILE__), '..', 'VERSION')
).chomp.freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSqlTagger

Returns a new instance of SqlTagger.



23
24
25
26
# File 'lib/sql_tagger.rb', line 23

def initialize
  @exclusion_pattern = %r{\A#{RbConfig::CONFIG['prefix']}|/gems/}
  @exclusion_cache = Set.new
end

Class Attribute Details

.defaultSqlTagger

Returns default SqlTagger to use.

Returns:



62
63
64
# File 'lib/sql_tagger.rb', line 62

def default
  @default
end

Instance Attribute Details

#custom_tag_prefixString, #call

Returns a string or a proc which resolves to a string to prefix the call trace tag.

Returns:

  • (String, #call)

    a string or a proc which resolves to a string to prefix the call trace tag



12
13
14
# File 'lib/sql_tagger.rb', line 12

def custom_tag_prefix
  @custom_tag_prefix
end

#exclusion_cacheSet (readonly)

Returns set that holds stack strings we skipped before.

Returns:

  • (Set)

    set that holds stack strings we skipped before



21
22
23
# File 'lib/sql_tagger.rb', line 21

def exclusion_cache
  @exclusion_cache
end

#exclusion_patternRegexp

Returns regular expression used to match stack strings we should skip (usually because such stack strings aren’t specific enough, like stack strings where the file belongs to a gem).

Returns:

  • (Regexp)

    regular expression used to match stack strings we should skip (usually because such stack strings aren’t specific enough, like stack strings where the file belongs to a gem)



18
19
20
# File 'lib/sql_tagger.rb', line 18

def exclusion_pattern
  @exclusion_pattern
end

Instance Method Details

#tag(sql) ⇒ String

Returns the given query string with a string from Kernel#caller prepended as a comment that reveals what code triggered the query.

For example, given “SELECT 1”, this will return something like “/* program.rb:25:in ‘some_method’ */ SELECT 1”.

Parameters:

  • sql (String)

    SQL query string

Returns:

  • (String)

    query string with a comment at the beginning



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/sql_tagger.rb', line 36

def tag(sql)
  caller(2).each do |string|
    next if @exclusion_cache.member?(string)
    if string !~ @exclusion_pattern
      return "/* #{custom_tag_prefix_string} #{string} */ #{sql}"
    else
      @exclusion_cache.add(string)
    end
  end

  # Just in case we skip the whole stack somehow ...
  "/* SqlTagger#tag skipped the whole stack */ #{sql}"
end