Class: Spectre::MySQL::Client

Inherits:
Object
  • Object
show all
Includes:
Delegate
Defined in:
lib/spectre/mysql.rb

Instance Method Summary collapse

Constructor Details

#initialize(config, logger) ⇒ Client

Returns a new instance of Client.



39
40
41
42
43
44
45
# File 'lib/spectre/mysql.rb', line 39

def initialize config, logger
  @config = config['mysql'] || {}
  @logger = logger

  @result = nil
  @last_conn = nil
end

Instance Method Details

#mysql(name = nil) ⇒ Object



47
48
49
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
# File 'lib/spectre/mysql.rb', line 47

def mysql(name = nil, &)
  query = {}

  if !name.nil? and @config.key? name
    query.merge! @config[name]

    unless query['host']
      raise "No `host' set for MySQL client '#{name}'. Check your MySQL config in your environment."
    end

  elsif !name.nil?
    query['host'] = name
  elsif @last_conn.nil?
    raise 'No name given and there was no previous MySQL connection to use'
  end

  MySqlQuery.new(query).instance_eval(&) if block_given?

  unless name.nil?
    @last_conn = {
      host: query['host'],
      username: query['username'],
      password: query['password'],
      database: query['database'],
    }
  end

  @logger.info "Connecting to database #{query['username']}@#{query['host']}:#{query['database']}"

  client = ::Mysql2::Client.new(**@last_conn)

  res = []

  query['query']&.each do |statement|
    @logger.info("Executing statement '#{statement}'")
    res = client.query(statement, cast_booleans: true)
  end

  @result = res.map { |row| OpenStruct.new row } if res

  client.close
end

#resultObject



90
91
92
93
94
# File 'lib/spectre/mysql.rb', line 90

def result
  raise 'No MySQL query has been executed yet' unless @result

  @result
end