#!/usr/bin/perl
############################################################################
##                          Change History
##
##  $Log: DB.pm,v $
##  Revision 1.1  2001/02/19 23:28:40  web
##  Added to the project
##
##  Revision 1.4  2000/07/24 16:59:39  phkumar
##  Removed print statement from DESTROY method
##
##  Revision 1.3  2000/07/24 16:17:19  jswensen
##  Added History block
##
##
############################################################################

package DB;

use DBI;

sub new {
	my $class = shift;
	my $this = {};
	
	$this->{database}		= '';
	$this->{userid}		= '';
	$this->{password}		= '';
	
	$this->{dbh}			= 0;
	$this->{sth}			= 0;
	$this->{sql}			= "";
	$this->{record}		= {};
	
	$this->{debug} 		= 0;

	return bless $this, $class;
}

sub login {
	my $this = shift;
	if($this->{dbh} == 0) {
		$this->{dbh} = 
			DBI->connect(
				'dbi:Oracle:'.$this->{database}, 
				$this->{userid}, 
				$this->{password}, 
				{	PrintError		=> 0,
					AutoCommit		=> 0 # remember you have to commit all transactions.
				}  
			);
		if(!$this->{dbh}) {
			$this->halt("DB:login - ");
		}
	}
}

sub logout {
	my $this = shift;
	$this->finish();
	if($this->{dbh}) {
		$this->{dbh}->disconnect();
	}
}

sub query {
	my $this = shift;
	my $sql = shift;
	$this->login();
	if($this->{sth}) {
		$this->{sth}->finish;
	}
	if($this->{sql} ne $sql)  {
		$this->{sth} = $this->{dbh}->prepare($sql) || die $this->halt("DB:Query(prepare) - ");
	}
	$this->{sql} = $sql;
	if(@_) {
		for($i=0; $i <= $#_; $i++) {
			$this->{sth}->bind_param($i + 1, $_[$i]) || die $this->halt("DB:Query(bind) - ");
		}
	}
	my $success = $this->{sth}->execute() || die $this->halt("DB:Query(execute) - ");
	if(!$success) {
		$this->halt("DB:Query(execute) - ");
	}

}

sub next_record {
	my $this = shift;
	$this->{record} = $this->{sth}->fetchrow_hashref;
	if($this->{record} == undef) {
		if($this->{dbh}->err) {
			$this->halt("DB:next_record - ");
		}
		return 0;
	}
	return 1;
}

sub commit {
	my $this = shift;
	$this->{dbh}->commit;
}

sub rollback {
	my $this = shift;
	$this->{dbh}->rollback;
}

sub col {
	my $this = shift;
	return $this->{record}->{uc(shift)};
}

sub halt {
	my ($this, $msg) = @_;
	printf(
		qq{
			</td></tr></table><P><BR><P>
			<font size="+2" color="RED">
				%s %s:%s
			</font></body></html>\n}, 
		$msg, 
		$DBI::err, 
		$DBI::errstr
	);
	exit;
}

sub lock {
	my $this = shift;

}

sub unlock {
	my $this = shift;

}

sub finish {
	my $this = shift;
	if($this->{sth}) {
		$this->{sth}->finish;
	}
}

sub Freeze {
	my ($this, $_options) = @_;
	$this->logout();
	$this->{dbh}			= undef;
	$this->{sth}			= undef;
	$this->{sql}			= undef;
	$this->{record}		= undef;
	$this->UNIVERSAL::Freeze($_options);
}

sub DESTROY {
	my ($this) = shift;
	$this->logout();
}	
1;
