package SQL;

use strict;
use Pg;

sub new
{
 my $class = shift;
 my $self = { };
 return bless( $self, $class );
}

sub connect
{
 my $self = shift;
 my $cstr = '';
 my %args = ( host => 'localhost',
	      port => '5432',
 	      @_
 	    );
 $self->{sock} = Pg::connectdb("host=$args{host} dbname=$args{dbname} port=$args{port} user=$args{login} password=$args{password}");
 return 0 if( $self->{sock}->status != 0 );
 return 1;
}

sub error
{
 my $self = shift;
 my ( $msg ) = @_;
 return $self->{sock}->errorMessage if( !$msg );
 return "$msg: ". $self->{sock}->errorMessage;
}

sub query
{
 my $self = shift;
 my ( $query ) = @_;
 $self->{res} = $self->{sock}->exec($query);
 return 0 if( $self->{res}->resultStatus != 2 && $self->{res}->resultStatus != 1 );
 return $self->{res};
}

sub numRows
{
 my $self = shift;
 return $self->{res}->ntuples;
}

sub numFields
{
 my $self = shift;
 return $self->{res}->nfields;
}

sub fetchRow($)
{
 my $self = shift;
 my ($res) = @_;
 return $res->fetchrow;
}

sub fetchObject
{
 my $self = shift;
 my (@res_arr) = $self->{res}->fetchrow;
 my (%res_hash) = ();
 my $i = 0;
 for( ; $i<$self->numFields();$i++)
 {
  my $fname = $self->{res}->fname($i);
  $res_hash{$fname} = "1". $res_arr[$i];
 }
 return %res_hash;
}

sub OID
{
 my $self = shift;
 my ($res) = @_;
 return $res->oidStatus;
}
1