# wrapper class for db2 access
# author : Jayakrishnan Mundarath. (jayakris@cs.wisc.edu)

package DB2Wrap;

$VERSION = 1.0;

use DBI;
use DBD::DB2::Constants;
use DBD::DB2;


###### Functions SUMMARY ######
# 1. new : creates the object
# 2. setDB2Env : sets the DB2 client environment
# 3. getDB2Handle : creates a new connection to the requested DB - uses an existing one if there is
# 4. execDB2Cmd : executes the provided cmd. also binds parameters in the order provided
# 5. stopDB2 : disconnects an existing connection

sub new 
{
 my ($class,@params) = @_;

 # create an anonymous hash to hold our instance variables
 # this becomes our object once it is "blessed"
 my($this) = {};
 
 $this->{'DB_HANDLE'} = undef;
 
  # bless us as belonging to the DB2Wrap class
 bless ($this, $class);
 return $this;
}

sub setDB2Env
{
 # shift the argument stack to get a reference to the invoking object
 my ($this) = shift;
 my ($db2inst) = @_;

 ($ENV{'CLASSPATH'} = "/home/$db2inst/sqllib/java/sqlj.zip:/home/$db2inst/sqllib/function:/home/$db2inst/sqllib/java/db2java.zip:/home/$db2inst/sqllib/java/runtime.zip:.");
 ($ENV{'DB2INSTANCE'} = "$db2inst");
 ($ENV{'LD_LIBRARY_PATH'} = ":/home/$db2inst/sqllib/lib");
 ($ENV{'LIBPATH'} = ":/home/$db2inst/sqllib/lib");
}

sub getDB2Handle
{
    my($this) = shift;
    my($dbname,$username,$passwd) = @_;

    if(defined($this->{'DB_HANDLE'}))
    {
	return $this->{'DB_HANDLE'};
    }
    
    my($dbh) = DBI->connect($dbname,$username,$passwd);

    if (!defined($dbh)) 
    {
	$this->{'DB_HANDLE'} = undef;
	return -1;
    }

    $this->{'DB_HANDLE'} = $dbh;
    return $this->{'DB_HANDLE'};
}

sub execDB2Cmd
{ 
    my ($this) = shift;
    my ($sqlcmd,@bindparams) = @_;

    my ($dbh) = $this->{'DB_HANDLE'};

    $this->{'ERROR'} = "DB Handle Invalid!";
    defined($dbh) or return -1;
    
    my ($sth) = $dbh->prepare($sqlcmd);

    $this->{'ERROR'} = $dbh->errstr;
    defined($sth) or return -1;

    my ($count) = 0;
    $this->{'ERROR'} = "Bind Error.";
    while (defined($bindparams[$count]))
    {
	$sth->bind_param($count+1,$bindparams[$count]) or return -1;
	$count++;
    }
    
    if ( !($sth->execute()) )
    {
	$this->{'ERROR'} = $sth->errstr;
	return -1;
    }

    $this->{'ST_HANDLE'} = $sth;
    
    return $this->{'ST_HANDLE'};
}

sub stopDB2
{
    my ($this) = shift;

    my ($dbh) = $this->{'DB_HANDLE'};
    if(defined($dbh))
    {
	$dbh->disconnect;
    }
    $this->{'DB_HANDLE'} = undef;
    $this->{'ST_HANDLE'} = undef;
}

