Class: Flydata::TableDef::MysqlTableDef

Inherits:
Object
  • Object
show all
Defined in:
lib/flydata/table_def/mysql_table_def.rb

Constant Summary collapse

PROC_override_varchar =

Check and set the varchar(char) size which is converted from length to byte size. On Mysql the record size of varchar(char) is a length of characters. ex) varchar(6) on mysql -> varchar(18) on flydata

->(type, mysql_type, flydata_type) do
  return type unless %w(char varchar).include?(mysql_type)
  if type =~ /\((\d+)\)/
    # expect 3 byte UTF-8 character
    "#{flydata_type}(#{$1.to_i * 3})"
  else
    raise "Invalid varchar type. It must be a bug... type:#{type}"
  end
end
PROC_override_varbinary =
->(type, mysql_type, flydata_type) do
  return type unless %w(binary varbinary).include?(mysql_type)
  if type =~ /\((\d+)\)/
    # expect 2 bytes for each original byte + 2 bytes for the prefix
    # ex) 4E5DFF => "0x4e5dff"
    "#{flydata_type}(#{$1.to_i * 2 + 2})"
  else
    raise "Invalid varbinary type. It must be a bug... type:#{type}"
  end
end
TYPE_MAP_M2F =
{
  'bigint' => {type: 'int8'},
  'binary' => {type: 'binary', override: PROC_override_varbinary},
  'bit' => {type: 'bit'},
  'blob' => {type: 'varbinary(65535)'},
  'bool' => {type: 'int1'},
  'boolean' => {type: 'int1'},
  'char' => {type: 'varchar', override: PROC_override_varchar},
  'date' => {type: 'date'},
  'datetime' => {type: 'datetime'},
  'dec' => {type: 'numeric'},
  'decimal' => {type: 'numeric'},
  'double' => {type: 'float8'},
  'double precision' => {type: 'float8'},
  'enum' => {type: 'enum'},
  'fixed' => {type: 'numeric'},
  'float' => {type: 'float4'},
  'int' => {type: 'int4'},
  'integer' => {type: 'int4'},
  'longblob' => {type: 'varbinary(4294967295)'},
  'longtext' => {type: 'text'},
  'mediumblob' => {type: 'varbinary(16777215)'},
  'mediumint' => {type: 'int3'},
  'mediumtext' => {type: 'text'},
  'numeric' => {type: 'numeric'},
  'set' => {type: 'set'},
  'smallint' => {type: 'int2'},
  'text' => {type: 'text'},
  'time' => {type: 'time'},
  'timestamp' => {type: 'datetime'},
  'tinyblob' => {type: 'varbinary(255)'},
  'tinyint' => {type: 'int1'},
  'tinytext' => {type: 'text'},
  'varbinary' => {type: 'varbinary', override: PROC_override_varbinary},
  'varchar' => {type: 'varchar', override: PROC_override_varchar},
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table_def, table_name, columns, default_charset, comment) ⇒ MysqlTableDef

Returns a new instance of MysqlTableDef.



86
87
88
89
90
91
92
# File 'lib/flydata/table_def/mysql_table_def.rb', line 86

def initialize(table_def, table_name, columns, default_charset, comment)
  @table_def = table_def
  @table_name = table_name
  @columns = columns
  @default_charset = default_charset
  @comment = comment
end

Instance Attribute Details

#columnsObject (readonly)

Returns the value of attribute columns.



147
148
149
# File 'lib/flydata/table_def/mysql_table_def.rb', line 147

def columns
  @columns
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



147
148
149
# File 'lib/flydata/table_def/mysql_table_def.rb', line 147

def table_name
  @table_name
end

Class Method Details

._create(io) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/flydata/table_def/mysql_table_def.rb', line 94

def self._create(io)
  table_def = ''
  table_name = nil
  columns = []
  default_charset = nil
  comment = nil

  position = :before_create_table

  io.each_line do |line|
    case position
    when :before_create_table
      if line =~ /CREATE TABLE `(.*?)`/
        position = :in_create_table
        table_name = $1
        table_def += line.chomp
        next
      end

    when :in_create_table
      table_def += line.chomp

      stripped_line = line.strip
      # `col_smallint` smallint(6) DEFAULT NULL,
      if stripped_line.start_with?('`')
        columns << parse_one_column_def(line)
      # PRIMARY KEY (`id`)
      elsif stripped_line.start_with?("PRIMARY KEY")
        parse_key(line, columns)
      #) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='test table';
      elsif stripped_line.start_with?(')')
        default_charset = $1 if line =~ /DEFAULT CHARSET\s*=\s*([^\s]+)/
        comment = $1 if /COMMENT='((?:\\'|[^'])*)'/.match(line)
        position = :after_create_table
      elsif stripped_line.start_with?("KEY")
        # index creation.  No action required.
      elsif stripped_line.start_with?("CONSTRAINT")
        # constraint definition.  No acction required.
      elsif stripped_line.start_with?("UNIQUE KEY")
        parse_key(line, columns, :unique)
      else
        # "Unknown table definition. Skip. (#{line})"
      end

    when :after_create_table
      unless columns.any? {|column| column[:primary_key]}
        raise TableDefError, {error: "no primary key defined", table: table_name}
      end
      break
    end
  end
  position == :after_create_table ? [table_def, table_name, columns, default_charset, comment] : nil
end

.convert_to_flydata_type(type) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/flydata/table_def/mysql_table_def.rb', line 67

def self.convert_to_flydata_type(type)
  TYPE_MAP_M2F.each do |mysql_type, type_hash|
    flydata_type = type_hash[:type]
    if /^#{mysql_type}\(|^#{mysql_type}$/.match(type)
      ret_type = type.gsub(/^#{mysql_type}/, flydata_type)
      if type_hash[:override]
        ret_type = type_hash[:override].call(ret_type, mysql_type, flydata_type)
      end
      return ret_type
    end
  end
  nil
end

.create(io) ⇒ Object



81
82
83
84
# File 'lib/flydata/table_def/mysql_table_def.rb', line 81

def self.create(io)
  params = _create(io)
  params ? self.new(*params) : nil
end

.parse_one_column_def(query) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/flydata/table_def/mysql_table_def.rb', line 159

def self.parse_one_column_def(query)
  line = query.strip
  line = line[0..-2] if line.end_with?(',')
  pos = 0
  cond = :column_name
  column = {}

  while pos < line.length
    case cond
    when :column_name  #`column_name` ...
      pos = line.index(' ', 1)
      column[:column] = if line[0] == '`'
                        line[1..pos-2]
                      else
                        line[0..pos-1]
                      end
      cond = :column_type
      pos += 1
    when :column_type  #... formattype(,,,) ...
      pos += 1 until line[pos] != ' '
      start_pos = pos
      pos += 1 until line[pos].nil? || line[pos] =~ /\s|\(/

      # meta
      if line[pos] == '('
        #TODO: implement better parser
        pos = line.index(')', pos)
        pos += 1
      end

      # type
      type = line[start_pos..pos-1]
      column[:type] = convert_to_flydata_type(type)

      cond = :options
    when :options
      column[:type] += ' unsigned' if line =~ /unsigned/i
      column[:auto_increment] = true if line =~ /AUTO_INCREMENT/i
      column[:not_null] = true if line =~ /NOT NULL/i
      column[:unique] = true if line =~ /UNIQUE/i
      if /DEFAULT\s+((?:[^'\s]+\b)|(?:'(?:\\'|[^'])*'))/i.match(line)
        val = $1
        val = val.slice(1..-1) if val.start_with?("'")
        val = val.slice(0..-2) if val.end_with?("'")
        column[:default] = val == "NULL" ? nil : val
      end
      if /COMMENT\s+'(((?:\\'|[^'])*))'/i.match(line)
        column[:comment] = $1
      end
      if block_given?
        column = yield(column, query, pos)
      end
      break
    else
      raise "Invalid condition. It must be a bug..."
    end
  end
  column
end

Instance Method Details

#to_flydata_tabledefObject



149
150
151
152
153
154
155
156
157
# File 'lib/flydata/table_def/mysql_table_def.rb', line 149

def to_flydata_tabledef
  tabledef = { table_name: @table_name,
               columns: @columns,
             }
  tabledef[:default_charset] = @default_charset if @default_charset
  tabledef[:comment] = @comment if @comment

  tabledef
end