Skip to content

Instantly share code, notes, and snippets.

@winebarrel winebarrel/tiny_mysql.rb
Last active Jan 20, 2017

Embed
What would you like to do?
https://goo.gl/HPNOeb sha1: 3149baf94ad92fc4254e4864d5b4faa53dc191b0
require 'open3'
class TinyMysql
attr_reader :mysql_command
attr_reader :defaults_extra_file
attr_reader :host
attr_reader :port
attr_reader :username
attr_reader :database
def initialize(options = {})
@mysql_command = options[:mysql_command] || 'mysql'
@defaults_extra_file = options[:defaults_extra_file]
@host = options[:host] || 'localhost' unless @defaults_extra_file
@port = options[:port]
@username = options[:username] || 'root' unless @defaults_extra_file
@password = options[:password]
@database = options[:database]
end
def query(sql)
out, err, status = Open3.capture3(*cmd_with_args, :stdin_data => sql)
status.success? or raise err
parse(out)
end
private
def cmd_with_args
list = []
list << {'MYSQL_PWD' => @password} if @password
list << @mysql_command
list << "--defaults-extra-file=#{@defaults_extra_file}" if @defaults_extra_file
list << '-h' << @host if @host
list << '-P' << @port if @port
list << '-u' << @username if @username
list << @database if @database
list
end
def parse(out)
out = out.split("\n")
columns = (out.shift || '').split("\t")
out.map do |row|
Hash[columns.zip(row.split("\t"))]
end
end
end
#!/usr/bin/env ruby
# ---
require 'open-uri'
require 'digest/sha1'
tm = open('https://goo.gl/HPNOeb', &:read)
Digest::SHA1.hexdigest(tm) == '3149baf94ad92fc4254e4864d5b4faa53dc191b0' or raise 'checksum error'
eval tm
# ---
require 'pp'
mysql = TinyMysql.new(username: 'scott', password: 'tiger', database: 'mysql')
pp mysql.query('show tables')
# => [{"Tables_in_mysql"=>"columns_priv"},
# {"Tables_in_mysql"=>"db"},
# {"Tables_in_mysql"=>"event"},
# {"Tables_in_mysql"=>"func"},
# {"Tables_in_mysql"=>"general_log"},
# {"Tables_in_mysql"=>"help_category"},
# {"Tables_in_mysql"=>"help_keyword"},
# {"Tables_in_mysql"=>"help_relation"},
# {"Tables_in_mysql"=>"help_topic"},
# {"Tables_in_mysql"=>"innodb_index_stats"},
# {"Tables_in_mysql"=>"innodb_table_stats"},
# {"Tables_in_mysql"=>"ndb_binlog_index"},
# {"Tables_in_mysql"=>"plugin"},
# {"Tables_in_mysql"=>"proc"},
# {"Tables_in_mysql"=>"procs_priv"},
# {"Tables_in_mysql"=>"proxies_priv"},
# {"Tables_in_mysql"=>"servers"},
# {"Tables_in_mysql"=>"slave_master_info"},
# {"Tables_in_mysql"=>"slave_relay_log_info"},
# {"Tables_in_mysql"=>"slave_worker_info"},
# {"Tables_in_mysql"=>"slow_log"},
# {"Tables_in_mysql"=>"tables_priv"},
# {"Tables_in_mysql"=>"time_zone"},
# {"Tables_in_mysql"=>"time_zone_leap_second"},
# {"Tables_in_mysql"=>"time_zone_name"},
# {"Tables_in_mysql"=>"time_zone_transition"},
# {"Tables_in_mysql"=>"time_zone_transition_type"},
# {"Tables_in_mysql"=>"user"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.