# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
package SimpleDbConnect;

use strict;
use warnings;
use Carp qw/ cluck /;

use Db::DbConnect;
use Logging;

sub new {
  my ($self, $dbType, $dbUser, $dbPw, $dbDB, $dbServer) = @_;
    
  my $dbh = Db::DbConnect::getDbConnect($dbType, $dbUser, $dbPw, $dbDB, $dbServer);
    
  unless (ref($dbh) =~ /HASH/ && ref( $dbh->{'EXECUTE'}) =~ /CODE/) {
    Logging::warning('Failed to connect to database');
    return undef;
  }

  return bless({'_dbh' => $dbh}, $self);
}

sub queryList {
  my ($self, $sql) = @_;
  my @list;
  
  if ($self->getDbh()->{'EXECUTE'}->($sql)) {
    my $ptrRow;
    while ($ptrRow = $self->getDbh()->{'FETCHROW'}->()) {
      push @list, @{$ptrRow}[0];
    }
  } 
  
  $self->getDbh()->{'FINISH'}->();

  return @list;
}

sub queryTable {
  my ($self, $sql) = @_;

  my @table;
  
  if ($self->getDbh()->{'EXECUTE'}->($sql)) {
    my $ptrRow;
    while ($ptrRow = $self->getDbh()->{'FETCHHASH'}->()) {
      push @table, $ptrRow;
    }
  } 
  
  $self->getDbh()->{'FINISH'}->();

  return @table;
}

sub queryMaxOneRow {
  my ($self, $sql) = @_;
  my @table = $self->queryTable($sql);
  if (scalar(@table) >= 1) {
    return $table[0];
  } else {
    return undef;
  }
}

sub queryOneRow {
  my ($self, $sql) = @_;

  my @table = $self->queryTable($sql);
  if (@table != 1) {
    cluck();
    Logging::warning('Expected to have exactly one row in result set');
    return undef;
  }

  return $table[0];
}


sub queryOneValue {
  my ($self, $sql) = @_;
  my @list = $self->queryList($sql);

  if (@list != 1) {
    cluck();
    Logging::warning('Expected to have exactly one row in result set');
    return undef;
  }

  return $list[0];
}

sub getDbh {
  my ($self) = @_;
  return $self->{_dbh};
}

1;
