#!/usr/bin/env ruby

# msqlexport.rb written by itacchi (DATE Ken) 2000-
# That's sample program for Ruby/mSQL.
# msqlexport.rb is a `msqlexport' clone.

require 'getopts'
require 'msql'



def dumpTable(client, table, separator, quote, escape, verbose=false)

  # valid only one charactor
  separator = separator ? separator[0,1] : ','
  escape    = escape    ? escape[0,1]    : '\\'
  quote     = quote[0,1] if quote

  if verbose
    STDERR.print "Sending SELECT query...\n"
  end

  query_string = "SELECT * FROM #{table}"
  client.query query_string
  result = client.store_result

  if verbose
    STDERR.print "Retrieved #{result.num_rows} rows. Processing...\n"
  end

  result.each_row do |row|
    for i in 0...result.num_fields
      if quote
        str = row[i].gsub(quote, escape+quote)
        print "#{quote}#{str}#{quote}"
      else
        str = row[i].gsub(separator, escape+separator)
        print "#{str}"
      end
      if (i < result.num_fields - 1)
        print separator
      end
    end
    print "\n"
  end

end



# print usage
def usage
  print <<_EOL_


usage:  msqlexport [-h host] [-v] [-s Char] [-q Char] [-e Char] database table

        Produce an ASCII export of the table.

        -v              Verbose
        -s Char         Use the character Char as the separation character
                        Default is a comma.
        -q Char         Quote each value with the specified character
        -e Char         Use the specifed Char as the escape character
                        Default is \

_EOL_
end



# --- main process

# parse option
opts = getopts("v", "h:", "s:", "q:", "e:")

# parse database name and table name
database  = ARGV.shift
table     = ARGV.shift

# don't specified database or table
unless database and table
  usage
  exit
end


host      =  $OPT_h
separator = ($OPT_s || ',')
quote     =  $OPT_q
escape    = ($OPT_e || '\\')
verbose   =  $OPT_v


# create mSQL client instance
if verbose
  STDERR.printf "Connecting to %s...\n", host ? host : "localhost"
end
client = Msql.connect host

# select database
if verbose
  STDERR.printf "Selecting data base #{database}...\n"
end
client.select_db database

# dump table
dumpTable(client, table, separator, quote, escape, verbose)

# close connection
if verbose
  STDERR.printf "Disconnecting from %s...\n", host ? host : "localhost"
end
client.close

print "\n"
