Class: Shiba::Parsers::MysqlSelectFields

Inherits:
Object
  • Object
show all
Defined in:
lib/shiba/parsers/mysql_select_fields.rb

Overview

Extracts table name and columns from queries formatted by ‘show warnings’.

Constant Summary collapse

BACKTICK =
"`"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sql) ⇒ MysqlSelectFields

Returns a new instance of MysqlSelectFields.



7
8
9
10
# File 'lib/shiba/parsers/mysql_select_fields.rb', line 7

def initialize(sql)
  @sql = sql
  @sc = ShibaStringScanner.new(@sql)
end

Instance Attribute Details

#scObject (readonly)

Returns the value of attribute sc.



11
12
13
# File 'lib/shiba/parsers/mysql_select_fields.rb', line 11

def sc
  @sc
end

Instance Method Details

#parse_fieldsObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/shiba/parsers/mysql_select_fields.rb', line 19

def parse_fields
  tables = {}

  sc.scan(%r{/\*.*?\*/ select })

  while !sc.scan(/ from/i)
    sc.scan(/distinct /)

    if sc.scan(/\w+\(/)
      parens = 1
      while parens > 0
        case sc.getch
        when '('
          parens += 1
        when ')'
          parens -= 1
        end
      end
      sc.scan(/ AS /)
      tick_match
      # parse function
    elsif sc.scan(/`(.*?)`\.`(.*?)`\.`(.*?)` AS `(.*?)`/)
      db = sc[1]
      table = sc[2]
      col = sc[3]

      tables[table] ||= []
      tables[table] << col

    elsif sc.scan(/`(.*?)`\.`(.*?)` AS `(.*?)`/)
      table = sc[1]
      col = sc[2]

      tables[table] ||= []
      tables[table] << col
    elsif sc.scan(/\(`(.*?)`\.`(.*?)` collate \w+\) AS `(.*?)`/)
      table = sc[1]
      col = sc[2]

      tables[table] ||= []
      tables[table] << col
    elsif sc.scan(/(\d+|NULL|'.*?') AS `(.*?)`/m)
    else
      if ENV['SHIBA_DEBUG']
        raise Shiba::Error.new("unknown stuff: in #{@sql}: #{@sc.rest}")
      end
      return {}
    end

    sc.scan(/,/)
  end

  # resolve table aliases
  if sc.scan(/ `.*?`\.`(.*?)` `(.*?)`/)
    table       = sc[1]
    table_alias = sc[2]

    if tables[table_alias]
      tables[table] = tables[table_alias]
      tables.delete(table_alias)
    end
  end

  tables
end

#tick_matchObject



15
16
17
# File 'lib/shiba/parsers/mysql_select_fields.rb', line 15

def tick_match
  sc.match_quoted_double_escape(BACKTICK)
end