Sha256: 18965e264abb6471f1d85044d47c628d82fcb304ce46521902421ebf3a2bb476

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

require_relative '../../table_def'

module Mysql
  class QueryParser
    # Return hash object
    def parse(query)
    end
  end

  class AlterTableAddColumnParser < QueryParser
    # Return hash object or array
    # {
    #   alter_action : "add_column",
    #   table_name : table_name,
    #   column : {
    #     name: column_name,
    #     type: column_type,
    #     not_null: [true|false],
    #     default: default_value,
    #     position: [first|last],
    #     after: column_name
    #   }
    # }
    def parse(query)
      do_parse(query)
    rescue
      $log.error("Failed to parse query. query:'#{query}' error:#{$!}")
      raise
    end

    private

    def do_parse(query)
      m = /^\s*alter\s+table\s+`?(?<table_name>[^\s]+)`?\s+add\s+column\s+/i.match(query)
      table_name = m['table_name']
      query = query[m[0].length..-1]

      columns = if query[0] == '('
                  query = query[1..-2] # delete parenthesis (...,...,...)
                  parse_multiple_columns(query)
                else
                  [parse_one_column(query)]
                end
      columns.collect do |col|
        {
          subtype: :add_column,
          table_name: table_name,
          column: col
        }
      end
    end

    def parse_one_column(query)
      Flydata::TableDef::MysqlTableDef.parse_one_column_def(query) do |column, query, pos|
        option_str = " " + query[pos..-1]
        if /\sFIRST/i.match(option_str)
          column[:position] = :first
        elsif /\sAFTER\s+`?([^`]+)`?/i.match(option_str)
          column[:after] = $1
        end
        column
      end
    end

    def parse_multiple_columns(query)
      raise "Not supported to add multiple columns"
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
flydata-0.1.9 lib/flydata/fluent-plugins/mysql/query_parser.rb
flydata-0.1.8 lib/flydata/fluent-plugins/mysql/query_parser.rb