matsuda
6/4/2009 - 4:08 AM

table_schema_info.rb

#!/usr/bin/env ruby
require 'optparse'
require "rubygems"
require "activerecord"

host = 'localhost'
password = ''
username = db = nil
help = ''

OptionParser.new do |opt|
  opt.version = '0.0.1'
  opt.on('-h [HOST]') {|v| host = v}
  opt.on('-u USERNAME') {|v| username = v}
  opt.on('-p [PASSWORD]') {|v| password = v}
  opt.on('-d DB') {|v| db = v}
  opt.permute!(ARGV)
  help = opt.help
end

unless username && db
  puts help
  exit!
end

ActiveRecord::Base.establish_connection(
  :adapter => 'mysql',
  :host => host,
  :username => username,
  :password => password,
  :database => db
)
connection = ActiveRecord::Base.connection
tables = connection.tables

# columns = tables.inject({}) do |result, table|
#   result[table] = connection.columns(table)
#   result
# end

File.open("table_columns.txt", "w") do |f|
  tables.inject({}) do |result, table|
    f.puts table
    f.puts '=' * 50
    connection.execute("SHOW FIELDS FROM #{table}").each do |field|
      f.puts "● #{field[0]} : #{field[1]}"
    end
    f.puts '-' * 50;
    f.puts
  end
end