Class: Mysql2xxxx::Writer

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

Direct Known Subclasses

CSV, JSON, XML

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Writer

Returns a new instance of Writer.



6
7
8
# File 'lib/mysql2xxxx/writer.rb', line 6

def initialize(options = {})
  @properties = Properties.new options
end

Instance Attribute Details

#propertiesObject (readonly)

Returns the value of attribute properties.



4
5
6
# File 'lib/mysql2xxxx/writer.rb', line 4

def properties
  @properties
end

Instance Method Details

#closeObject



57
58
59
60
61
# File 'lib/mysql2xxxx/writer.rb', line 57

def close
  result.free
  dbh.close
  @dead = true
end

#dbhObject



31
32
33
34
35
36
37
38
39
# File 'lib/mysql2xxxx/writer.rb', line 31

def dbh
  return @dbh if @dbh.is_a? ::Mysql
  @dbh = ::Mysql.init
  @dbh.options ::Mysql::SET_CHARSET_NAME, properties.charset
  @dbh.real_connect properties.host, properties.user, properties.password, properties.database, properties.port, properties.socket
  # so that we can use_result instead of store_result
  @dbh.query_with_result = false
  @dbh
end

#keysObject



10
11
12
# File 'lib/mysql2xxxx/writer.rb', line 10

def keys
  @keys ||= result.fetch_fields.map { |field| field.name }
end

#last_statementObject



14
15
16
17
18
19
20
21
22
23
# File 'lib/mysql2xxxx/writer.rb', line 14

def last_statement
  return @last_statement if @last_statement.is_a? ::String
  statements = properties.execute.split(';').select { |statement| statement.to_s.strip.length > 0 }
  @last_statement = statements.pop
  statements.each do |statement|
    dbh.query statement
    # but we're not using the results
  end
  @last_statement
end

#resultObject



25
26
27
28
29
# File 'lib/mysql2xxxx/writer.rb', line 25

def result
  return @result if @result.is_a? ::Mysql::Result
  dbh.query last_statement
  @result = dbh.use_result
end

#stream_arraysObject



41
42
43
44
45
46
47
# File 'lib/mysql2xxxx/writer.rb', line 41

def stream_arrays
  raise "dead connection" if @dead
  while ary = result.fetch_row do
    yield ary
  end
  close
end

#stream_hashesObject



49
50
51
52
53
54
55
# File 'lib/mysql2xxxx/writer.rb', line 49

def stream_hashes
  raise "dead connection" if @dead
  while hsh = result.fetch_hash do
    yield hsh
  end
  close
end

#to_path(path) ⇒ Object



75
76
77
78
79
80
# File 'lib/mysql2xxxx/writer.rb', line 75

def to_path(path)
  f = ::File.open(path, 'w')
  to_file f
  f.close
  nil
end

#to_sObject



63
64
65
66
67
68
# File 'lib/mysql2xxxx/writer.rb', line 63

def to_s
  s = ::StringIO.new
  to_file s
  s.rewind
  s.read
end

#to_stdoutObject



70
71
72
73
# File 'lib/mysql2xxxx/writer.rb', line 70

def to_stdout
  to_file $stdout
  nil
end