#!/usr/bin/env ruby

require "odbc"

dsn,u,pw=ARGV[0,3]

puts "Connecting to [#{dsn}, #{u}, #{pw}]"
c=ODBC::connect(dsn, u, pw) or die "Can't connect: " + ODBC::error + "\n"

puts "Connected: " + c.connected?.to_s + "\n"

puts "\nData-types:\n"

[[ODBC::SQL_INTEGER,"integer"],
  [ODBC::SQL_BIGINT,"bigint"],
  [ODBC::SQL_NUMERIC,"numeric"],
  [ODBC::SQL_DECIMAL,"decimal"],
  [ODBC::SQL_DATETIME,"datetime"],
  [ODBC::SQL_FLOAT,"float"],
  [ODBC::SQL_DOUBLE,"double"],
  [ODBC::SQL_TIMESTAMP,"timestamp"],
  [ODBC::SQL_VARCHAR,"varchar"],
  [ODBC::SQL_LONGVARBINARY,"longvarbinary"],
  [ODBC::SQL_DATE,"date"],
  [ODBC::SQL_TIME,"time"],
  [ODBC::SQL_TYPE_TIMESTAMP,"type_timestamp"]].each {|t,n|
  puts "\nType #{n}:"
  c.types(t).each_hash(false) {|h|
    puts "Native: #{h['TYPE_NAME']}"
    h.each {|k,v|
      printf("  %-20s %s\n", k+":",v)
    }
  }
}

c.clear_error

puts "\n"
def test(c, t)
  begin
    print "\nTrying type #{t.to_s} (#{t.class}): "
    r=c.get_info(t).to_s
    puts "ret=[#{r}]"
  rescue NoMethodError,ArgumentError,ODBC::Error => s
    puts "\n  Exception: [#{s}]"
    ce=c.error.to_s
    e="[" + ODBC::error.to_s + " " + ODBC::info.to_s + "]"
    puts "  Error: #{e}"
    c.clear_error
    ce=c.error.to_s
    e=ODBC::error.to_s + ODBC::info.to_s
    puts "  After clearing, error: #{e}"
  end
end

def odbctype(c, t, default="")
  i=nil
  begin
    i=c.get_info(t)[0]['TYPE_NAME'] || c.get_info(t)[0]['NAME']
  rescue default
    i || default
  end
end

def odbctypeprecision(c,t, default)
  i=-1
  begin
    i=c.get_info(t)[0]
    i['COLUMN_SIZE'] || i['PRECISION']
  rescue default
    i || default
  end
end

test(c, 17)

puts "Testing for a selection of info types"

%w(
    17
    SQL_CURSOR_ROLLBACK_BEHAVIOR SQL_DYNAMIC_CURSOR_ATTRIBUTES1
    SQL_KEYWORDS SQL_LIKE_ESCAPE_CLAUSE SQL_COLUMN_ALIAS
    SQL_ORDER_BY_COLUMNS_IN_SELECT
).each {|t|
  test(c,t)
}

puts "Getting types:"

c.do("drop table timtest") rescue nil
strt=odbctype(c, ODBC::SQL_VARCHAR, "varchar NOT FOUND")
dtt=odbctype(c, ODBC::SQL_DATETIME.to_i, odbctype(c, ODBC::SQL_TIMESTAMP, "datetime NOT FOUND").to_i)

puts "String type is [#{strt}], date-time is [#{dtt}]"

c.do("create table timtest (id integer, str #{strt}, dob #{dtt})") rescue nil
c.do("insert into timtest values (1, 'foo', {ts '2005-12-22 17:48:01'})")
c.do("insert into timtest values (2, 'bar', {ts '2005-12-22 17:59:01'})")

puts "\nGetting column data for timtest"

c.columns("timtest").each {|a|
  puts a.to_a.join(" | ")
}

puts "I'm done."

