class MysqlParser

Constants

CLEAN_COLUMNS_RE
DEFAULT_NAME
DEFAULT_TABLE
VERSION

Attributes

tables[R]

Public Class Methods

new() click to toggle source
# File lib/mysql_parser.rb, line 39
def initialize
  reset
end
parse(input, &block) click to toggle source
# File lib/mysql_parser.rb, line 34
def self.parse(input, &block)
  parser = new.parse(input, &block)
  block ? parser : parser.tables
end

Public Instance Methods

parse(input) { |context, name| ... } click to toggle source
# File lib/mysql_parser.rb, line 56
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, statement_parser, value_parser, block_given =
    @name, @table, @columns, @statement_parser, @value_parser, block_given?

  input.each { |line|
    statement_parser.parse(line) { |context, *data|
      case context
        when :use
          name = data[0]
          yield context, name if block_given
        when :create
          table = data[0]
        when :column
          columns[table] << data[0] if table
        when :table
          yield context, name, table, columns[table] if block_given
          table = nil
        when :insert
          _table, _columns, _values = data

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

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

  @name, @table = name, table

  self
end
reset() click to toggle source
# File lib/mysql_parser.rb, line 43
def reset
  @name             = DEFAULT_NAME
  @table            = DEFAULT_TABLE

  @tables           = {}
  @columns          = Hash.new { |h, k| h[k] = [] }

  @value_parser     = ValueParser.new
  @statement_parser = StatementParser.new
end