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
89
90
91
92
93
94
95
96
97
98
99
100
101
|
# File 'lib/spectre/mysql.rb', line 51
def mysql(name = nil, &)
config = {}
if !name.nil? and @config.key? name
config.merge! @config[name]
unless config['host']
raise "No `host' set for MySQL client '#{name}'. Check your MySQL config in your environment."
end
elsif !name.nil?
config['host'] = name
elsif @last_conn
config['host'] = @last_conn[:host]
config['username'] = @last_conn[:username]
config['password'] = @last_conn[:password]
config['database'] = @last_conn[:database]
config['ssl'] = @last_conn[:ssl_mode]
else
raise 'No name given and there was no previous MySQL connection to use'
end
MySqlQuery.new(config).instance_eval(&) if block_given?
@last_conn = {
host: config['host'],
username: config['username'],
password: config['password'],
database: config['database'],
ssl_mode: (config['ssl'] || :required).to_sym,
}
@logger.info "Connecting to database #{@last_conn[:username]}@#{@last_conn[:host]}:#{@last_conn[:database]}"
client = ::Mysql2::Client.new(**@last_conn)
begin
res = nil
config['query']&.each do |statement|
@logger.info("Executing statement '#{statement}'")
res = client.query(statement, cast: false, cast_booleans: false)
end
@result = res.map { |row| OpenStruct.new(row) } if res
ensure
client.close
end
end
|