Class: MySql

Inherits:
DbInterface show all
Defined in:
lib/interface/mysql.rb

Constant Summary collapse

MYSQL_BATCH_SEP =
"\t"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ MySql

config is a hash with this form (like ActiveRecord’s):

host:     "localhost",
username: "myuser",
password: "mypass",
database: "somedatabase"



15
16
17
18
19
20
# File 'lib/interface/mysql.rb', line 15

def initialize(config)
  @db_host = config['host']
  @db_name = config['database']
  @username = config['username']
  @password = config['password']
end

Class Method Details

.avro_type(mysql_type) ⇒ Object



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
# File 'lib/interface/mysql.rb', line 162

def self.avro_type(mysql_type)
  # Refer to https://github.com/apache/sqoop/blob/trunk/src/java/org/apache/sqoop/manager/ConnManager.java#L172.

  case mysql_type

  # See https://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
  when /tinyint\(1\)/, /bool/, /boolean/
    'boolean'
  when /bigint/, /serial/
    'long'
  when /tinyint/, /smallint/, /mediumint/, /integer/, /int/
    'int'
  when /decimal/, /dec/
    'string'
  when /float/
    'float'
  when /double/
    'double'
  when /varchar\(\d+\)/
    'string'

  # See https://dev.mysql.com/doc/refman/5.0/en/date-and-time-type-overview.html.
  when /date/, /datetime/, /time/, /timestamp/
    'string'
  when /year/
    'int'

  # See https://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html.
  when /char/, /varchar/
    'string'
  when /binary/, /varbinary/
    'bytes'
  when /tinytext/, /text/, /longtext/
    'string'
  when /tinyblob/, /blob/, /longblob/
    'bytes'
  else
    raise "Unsupported MySQL data type: #{mysql_type}"
  end
end

.query(sql, db_host, db_name, username, password, &block) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/interface/mysql.rb', line 139

def self.query(sql, db_host, db_name, username, password, &block)
  cmd = %{
    mysql \\
      --batch \\
      --execute="SET NAMES 'utf8'; #{sql}" \\
      --host #{db_host} \\
      --user #{username} \\
      --password=#{password} \\
      --quick \\
      #{db_name}
  }

  Open3.popen3(cmd) do |i, o, e, wait_thr|
    while (line = o.gets)
      block.call(line.chop.split(MYSQL_BATCH_SEP))
    end

    if !wait_thr.value.success?
      raise "Error querying mysql\n\nQuery: #{cmd}\nSTDERR: #{e.read}\nSTATUS: #{wait_thr.value}"
    end
  end
end

Instance Method Details

#avro_types(table) ⇒ Object



124
125
126
127
128
129
130
131
132
133
# File 'lib/interface/mysql.rb', line 124

def avro_types(table)
  mysql_types = sql_schema(table)

  types = {}
  mysql_types.each do |k,v|
    types[k] = MySql.avro_type(v)
  end

  types
end

#data(table, min_id, max_id, &block) ⇒ Object



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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/interface/mysql.rb', line 50

def data(table, min_id, max_id, &block)
  columns = nil
  rows = []

  types = avro_types(table)

  sql = """
    SELECT *
    FROM #{table}
    WHERE id >= #{min_id}
      AND id <= #{max_id}
  """
  query(sql) do |line|
    # Get header.
    if columns.nil?
      columns = line
      next
    end

    # Construct row mapping column names to values of appropriate type.
    row = (0...columns.length).each_with_object({}) do |i, h|
      colname = columns[i]
      value = line[i]

      # NOTE: all non-null type values are wrapped in a mapping from type to value,
      # because that's what the Avro spec requires; see:
      #  - http://avro.apache.org/docs/current/spec.html#json_encoding
      #  - http://mail-archives.apache.org/mod_mbox/avro-user/201304.mbox/%3CCD86687D.E892E%[email protected]%3E

      # Handle nulls.
      if value == "NULL"
        h[columns[i]] = nil
        next
      end

      # Perform any necessary typecasts.
      type = types[colname]
      h[colname] = case type
      when 'boolean'
        { type => value.to_i.zero? }
      when 'int','long'
        { type => value.to_i }
      when 'float','double'
        { type => value.to_f }
      when 'bytes'
        { type => value }
      when 'string'
        { type => value }
      else
        raise "Unsupported type: #{type}"
      end
    end

    block.call(row)
  end
end

#max_id(table) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/interface/mysql.rb', line 38

def max_id(table)
  header_seen = false
  query("SELECT MAX(id) FROM #{table}") do |line|
    unless header_seen
      header_seen = true
      next
    end

    return line.first.to_i
  end
end

#query(sql, &block) ⇒ Object



135
136
137
# File 'lib/interface/mysql.rb', line 135

def query(sql, &block)
  MySql.query(sql, @db_host, @db_name, @username, @password, &block)
end

#schema(table) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/interface/mysql.rb', line 22

def schema(table)
  types = avro_types(table)

  schema = {
    type: "record",
    name: table,
    fields: []
  }

  types.each do |k,v|
    schema[:fields] << { name: k, type: ['null', v] }
  end

  schema
end

#sql_schema(table) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/interface/mysql.rb', line 107

def sql_schema(table)
  header_seen = false
  columns = {}

  query("DESCRIBE #{table}") do |line|
    if header_seen == false
      header_seen = true
      next
    end

    name, type = line[0], line[1]
    columns[name] = type
  end

  columns
end