Class: Jabara::MySQLBulk::Output

Inherits:
Jabara::MySQL::Output show all
Defined in:
lib/jabara/mysql_bulk/output.rb

Instance Method Summary collapse

Constructor Details

#initialize(schema:, tuple_size: 1000) ⇒ Output

Returns a new instance of Output.



7
8
9
10
11
12
13
# File 'lib/jabara/mysql_bulk/output.rb', line 7

def initialize(schema:, tuple_size:1000)
  @table_name = schema.table_name
  @schema = schema
  @tuple_size = tuple_size
  @column_keys = @schema.columns.map { |column| column[:key] }
  reset_buffer
end

Instance Method Details

#column_defObject



55
56
57
# File 'lib/jabara/mysql_bulk/output.rb', line 55

def column_def
  "(%s)" % @schema.columns.map {|column| "`%s`" % column[:key] }.join(", ")
end

#encode(repr) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/jabara/mysql_bulk/output.rb', line 15

def encode(repr)
  data = ::Jabara.data(repr)
  tuple_str = "(%s)" % @column_keys.map { |key| 
    mysql_value(data[key])
  }.join(", ")

  @buf << tuple_str
  @buf << ","
  @tuple_count = @tuple_count + 1

  if @tuple_count >= @tuple_size then
    return flush
  else 
    return nil
  end
end

#flushObject



32
33
34
35
36
37
38
39
# File 'lib/jabara/mysql_bulk/output.rb', line 32

def flush
  return nil if @tuple_count == 0

  terminate
  ret = @buf
  reset_buffer
  return ret
end

#insert_headObject



51
52
53
# File 'lib/jabara/mysql_bulk/output.rb', line 51

def insert_head
  "insert into `%s` %s values" % [@table_name, column_def]
end

#reset_bufferObject



41
42
43
44
# File 'lib/jabara/mysql_bulk/output.rb', line 41

def reset_buffer
  @buf = insert_head
  @tuple_count = 0
end

#terminateObject



46
47
48
49
# File 'lib/jabara/mysql_bulk/output.rb', line 46

def terminate
  @buf.chop!
  @buf << ";\n"
end

#validateObject



59
60
61
62
63
64
65
66
67
# File 'lib/jabara/mysql_bulk/output.rb', line 59

def validate
  @schema.columns.each do |column|
    return false, 'violate "not null" constraint.' if column[:constraints].include? :not_null and data.nil?
    valid, err = column[:type].validate(data)
    return false, err unless valid
  end

  return true, nil
end