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

Constant Summary collapse

VERSION =
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.



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

def initialize
  @exclusion_pattern = /^#{RbConfig::CONFIG['prefix']}|\/bundle\/|\/vendor\//
  @exclusion_cache = Set.new
end

Class Attribute Details

.defaultSqlTagger

Returns default SqlTagger to use.

Returns:



57
58
59
# File 'lib/sql_tagger.rb', line 57

def default
  @default
end

Instance Attribute Details

#exclusion_cacheSet (readonly)

Returns set that holds stack strings we skipped before.

Returns:

  • (Set)

    set that holds stack strings we skipped before



16
17
18
# File 'lib/sql_tagger.rb', line 16

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)



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

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



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/sql_tagger.rb', line 31

def tag(sql)
  caller(2).each do |string|
    next if @exclusion_cache.member?(string)
    if string !~ @exclusion_pattern
      return "/* #{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