require "phi" ; include Phi
require "rdb" ; include RDB

DEFAULT_PARAMS_FOR_INTERBASE = {
  "User_Name"     => "",
  "Password"      => "",
  "Database"      => "database.gdb",
  "DriverName"    => "Interbase",
  "BlobSize"      => "-1",
  "CommitRetain"  => "False",
  "ErrorResourceFile" => "",
  "LocaleCode"    => "0000",
  "RoleName"      =>"RoleName",
  "ServerCharSet" => "",
  "SQLDialect"    =>"1",
  "Interbase TransIsolation" => "ReadCommited",
  "WaitOnLocks"   => "True",
}

module RDB
  class SQLConnection
    def params=(v)
      case v
      when Hash
        params.clear
        v.each{|k,v|  params[k] = v }
      else
        super
      end
    end
  end
end

  def interbase_connection( server, user=nil, passwd=nil,params=DEFAULT_PARAMS_FOR_INTERBASE)
    ret = SQLConnection.new
    ret.driver_name = "InterBase"
    ret.vendor_lib="GDS32.DLL"
    ret.library_name="dbexpint.dll"
    ret.get_driver_func="getSQLDriverINTERBASE"
    ret.params = params
    ret.params["Database"] = server
    ret.params["User_Name"] = user if user
    if passwd && passwd != ''
      ret.params["Password"] = passwd
      ret.login_prompt = false 
    end
    ret
  end

class SQLConnection

  def new_query(sql=nil)
    ret = SQLClientDataSet.new
    ret.db_connection = self
    ret.command_type = CT_QUERY
    if sql
      ret.command_text = sql
      ret.open
    end
    return ret
  rescue
    puts "-- SQL is ..#{ret.sql_text}--"
    raise
  end
  alias query new_query

  def new_table(name=nil)
    ret = SQLClientDataSet.new
    ret.db_connection = self
    ret.command_type = RDB::CT_TABLE
    if name
      ret.command_text = name
      ret.open
    end
    return ret
  end
  alias table new_table

end

########

server = 'C:/Program Files/Common Files/Borland Shared/Data/employee.gdb'

con = interbase_connection( server , "SYSDBA" , "masterkey" )

table = con.new_table("country")
table.display   # OK

query = con.new_query
query.command_text = "select * from country where country='Japan'"
query.open
query.display

p query = con.new_query
query.command_text = "select * from country where country=:key"
p query.params.count
#query.params["key"] = "Japan"
query.open
query.display
