Class: Jabara::MySQLDump::Output

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

Instance Method Summary collapse

Methods inherited from Jabara::MySQL::Output

#encode

Constructor Details

#initialize(schema:, out_path:, fields_terminated_by: ',', fields_enclosed_by: '"', fields_escapted_by: '"', lines_terminated_by: "\n") ⇒ Output

Returns a new instance of Output.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/jabara/mysql_dump/output.rb', line 7

def initialize(schema:, out_path:,
               fields_terminated_by:',',
               fields_enclosed_by:'"', # TODO Not supported yet
               fields_escapted_by:'"', # TODO Not supported yet
               lines_terminated_by:"\n")
  @schema = schema
  @out_path = out_path

  @field_delimiter = fields_terminated_by
  @field_quote_str = fields_enclosed_by
  @escape_str = fields_escapted_by
  @line_delimiter = lines_terminated_by

  @column_keys = @schema.columns.map { |column| column[:key] }
  @file = File.open(@out_path, 'w')
  @buf = ''
end

Instance Method Details

#load_data_queryObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/jabara/mysql_dump/output.rb', line 43

def load_data_query
  query = <<SQL
load data infile '%s' into `%s`
character set %s
fields terminated by '%s'
 enclosed by '%s'
 escaped by '%s'
lines terminated by '%s'
;
SQL
  query % [@out_path,
           @schema.table_name,
           @char_set || 'utf8mb4',
           @field_delimiter,
           @field_quote_str,
           @escape_str,
           @line_delimiter]
end

#terminateObject



38
39
40
41
# File 'lib/jabara/mysql_dump/output.rb', line 38

def terminate
  @file.write(@buf.chomp(@line_delimiter))
  @file.close
end

#write(object_repr) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/jabara/mysql_dump/output.rb', line 25

def write(object_repr)
  begin
    @file.write(@buf)
    data = ::Jabara.data(object_repr)
    @buf = @column_keys.map { |key|
      mysql_value(data[key])
    }.join(@field_delimiter) + @line_delimiter
  rescue => e
    cleanup
    raise e # reraise
  end
end