Created
November 16, 2011 08:23
-
-
Save fakechris/1369573 to your computer and use it in GitHub Desktop.
Connect mysql via ssh tunnel, create active record obj automatically and processing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'URI' | |
require 'cgi' | |
require 'net/ssh/gateway' | |
require "mysql" | |
require 'active_record' | |
def connect_to(database, connection_opts) | |
args = {:adapter=>"mysql", :database=>database}.merge(connection_opts) | |
ActiveRecord::Base.establish_connection(args) | |
end | |
def declare_active_record_for entity_name | |
eval %" | |
class #{entity_name} < ActiveRecord::Base | |
end | |
"; | |
end | |
def declare_active_record_for_adgaga entity_name | |
eval %" | |
class #{entity_name} < ActiveRecord::Base | |
set_table_name \"#{entity_name.downcase}\" | |
end | |
"; | |
end | |
def as_entity_name table_name | |
table_name.capitalize | |
end | |
def generate_schema(database_name, connection_opts={}) | |
connect_to "information_schema", connection_opts | |
declare_active_record_for "Table" | |
table_names = Array.new | |
Table.find(:all, :conditions =>{ | |
:table_schema=>database_name}).each { | |
|i| table_names.push i.TABLE_NAME} | |
connect_to database_name, connection_opts | |
table_names.each { | |
|table| declare_active_record_for_adgaga as_entity_name(table)} | |
end | |
def build_query(params) | |
params.map do |name,values| | |
values.map do |value| | |
"#{CGI.escape name}=#{CGI.escape value}" | |
end | |
end.flatten.join("&") | |
end | |
def process_creatives(creativeKlass) | |
creativeKlass.where(:member_id => 10086).find_each do |creative| | |
puts creative.id | |
end | |
end | |
def do_activedb(dbname, user, pass, port) | |
generate_schema(dbname, :username=>user, :password=>pass, | |
:host=>'127.0.0.1', :port=>port) | |
eval "process_creatives(#{as_entity_name('creative')})" | |
end | |
def do_db(dbname, user, pass, port) | |
db = Mysql.init | |
db.options(Mysql::SET_CHARSET_NAME, 'utf8') | |
db.connect("127.0.0.1", dbname, user, pass, port) | |
sql = "select * from creative" | |
results = db.query(sql) | |
db.close | |
end | |
def fork_ssh_mysql(fn, ssh_host, ssh_user, host, dbname, user, pass) | |
gateway = Net::SSH::Gateway.new(ssh_host, ssh_user) | |
port = gateway.open(host,3306,13306) | |
child = fork do | |
fn.call(dbname, user, pass, port) | |
exit | |
end | |
puts "child: #{child}" | |
Process.wait | |
gateway.close(port) | |
end | |
fork_ssh_mysql(method(:do_activedb), "ssh_host", "ssh_user", | |
"hostname", "dbname", "user", "pass") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment