Class: FastInnodbImport

Inherits:
Object
  • Object
show all
Defined in:
lib/fast_innodb_import.rb

Constant Summary collapse

VERSION =
'0.0.2'
CMD_MAPPING =
{ "u" => :username, "h" => :host, "d" => :database, "p" => "password" }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ FastInnodbImport

Returns a new instance of FastInnodbImport.



11
12
13
# File 'lib/fast_innodb_import.rb', line 11

def initialize(options = {})
  self.options = options
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



9
10
11
# File 'lib/fast_innodb_import.rb', line 9

def options
  @options
end

#streamObject

Returns the value of attribute stream.



9
10
11
# File 'lib/fast_innodb_import.rb', line 9

def stream
  @stream
end

Class Method Details

.execute(argv, stream = nil) ⇒ Object



15
16
17
18
19
# File 'lib/fast_innodb_import.rb', line 15

def self.execute(argv, stream = nil)
  importer = self.new(options_from_argv(argv))
  importer.stream = stream
  importer.execute
end

.options_from_argv(argv) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/fast_innodb_import.rb', line 60

def self.options_from_argv(argv)
  options = { :db => {} }
  %w(u h d p).each do |key|
    if idx = argv.index("-#{key}")
      value = argv.at(idx + 1)
      options[:db][CMD_MAPPING[key]] = value if !value.match(/^\-/)
      argv.delete_at(idx)
      argv.delete_at(idx)
    end
  end
  options[:drop_keys] = argv.delete("--without-drop-keys").nil?
  options[:file_paths] = argv
  options
end

Instance Method Details

#executeObject



21
22
23
24
25
26
# File 'lib/fast_innodb_import.rb', line 21

def execute
  print_usage_and_exit_if_missing_options
  file_paths.each do |path|
    import_data_from_file_path(path)
  end
end

#import_data_from_file_path(path) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/fast_innodb_import.rb', line 28

def import_data_from_file_path(path)
  file_path = File.expand_path(path)
  return if !File.exists?(file_path)
  table_name = table_name_from_file_path(file_path)
  wc = `wc -l #{file_path}`.strip.to_i
  started = Time.now
  if stream
    stream.print "import %d rows from %s: " % [wc, file_path] if stream
    stream.flush
  end
  
  # create drop and create statements as long as we can
  drop_statement = index_drop_statement_for_table(table_name)
  create_statement = index_create_statement_for_table(table_name)
  
  query("TRUNCATE `#{table_name}`")
  query(drop_statement) if drop_keys?
  `#{self.class.import_command_prefix_from_options(options)} #{file_path}`
  query(create_statement) if drop_keys?
  
  # print stats if stream given
  if stream
    diff = Time.now - started
    per_sec = wc / diff
    stream.puts "%d (%d/sec)" % [diff, per_sec]
  end
end