Class: Nuggets::MySQL::Parser

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

Constant Summary collapse

DEFAULT_NAME =
'__DEFAULT__'
DEFAULT_TABLE =
'__DEFAULT__'
USE_RE =
/\AUSE\s+`(.+?)`/i
CREATE_TABLE_RE =
/\ACREATE\s+TABLE\s+`(.+?)`/i
TABLE_COLUMN_RE =
/\A\s+`(.+?)`/
FINISH_TABLE_RE =
/\A\).*;\Z/
INSERT_VALUES_RE =
/\AINSERT\s+INTO\s+`(.+?)`\s+(?:\((.+?)\)\s+)?VALUES\s*(.*);\Z/i
CLEAN_COLUMNS_RE =
/[\s`]+/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



50
51
52
# File 'lib/nuggets/mysql.rb', line 50

def initialize
  reset
end

Instance Attribute Details

#tablesObject (readonly)

Returns the value of attribute tables.



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

def tables
  @tables
end

Class Method Details

.parse(input, &block) ⇒ Object



45
46
47
48
# File 'lib/nuggets/mysql.rb', line 45

def self.parse(input, &block)
  parser = new.parse(input, &block)
  block_given? ? parser : parser.tables
end

Instance Method Details

#parse(input, &block) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/nuggets/mysql.rb', line 64

def parse(input, &block)
  unless block
    tables, block = @tables, lambda { |_, name, table, columns, values|
      ((tables[name] ||= {})[table] ||= []) << fields = {}

      values.each_with_index { |value, index|
        if column = columns[index]
          fields[column] = value
        end
      }
    }
  end

  name, table, columns, value_parser, block_given =
    @name, @table, @columns, @value_parser, block_given?

  input.each { |line|
    case line
      when USE_RE
        name = $1
        yield :use, name if block_given
      when CREATE_TABLE_RE
        table = $1
      when TABLE_COLUMN_RE
        columns[table] << $1 if table
      when FINISH_TABLE_RE
        yield :table, name, table, columns[table] if block_given
        table = nil
      when INSERT_VALUES_RE
        _table, _columns, _values = $1, $2, $3

        _columns = _columns.nil? ? columns[_table] :
          _columns.gsub(CLEAN_COLUMNS_RE, '').split(',')

        value_parser.parse(_values) { |values|
          block[:insert, name, _table, _columns, values]
        } unless _columns.empty?
    end
  }

  @name, @table = name, table

  self
end

#resetObject



54
55
56
57
58
59
60
# File 'lib/nuggets/mysql.rb', line 54

def reset
  @name         = DEFAULT_NAME
  @table        = DEFAULT_TABLE
  @tables       = {}
  @columns      = Hash.new { |h, k| h[k] = [] }
  @value_parser = ValueParser.new
end