#################################################################################
#
# $Header: SQLPlusSession.pm 14-jan-2005.10:56:06 ktlaw Exp $
#
# SQLPlusSession.pm
#
# Copyright (c) 2003, 2005, Oracle. All rights reserved.  
#
#    NAME
#      SQLPlusSession.pm - <one-line expansion of the name>
#
#    DESCRIPTION
#      <short description of component this file declares/defines>
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YYYY)
#       ktlaw      01/14/05 - add comments 
#       ktlaw      01/13/05 - ktlaw_new_repmgr
#       ktlaw      01/10/05 - created
################################################################################

#
# SQLPLusSession.pm - Implementation of BaseSession using an open pipe to a 
# SQLPlus child process. This can be used to run all SQL scripts directly
# rather than generating a script and then run it. A wrapper can be built
# on top of this class to achieve parallelism, i.e. executing SQL scripts using 
# multiple child processes.
#
package SQLPlusSession;
use BaseSession;
@ISA =("BaseSession");

use IO::Handle;
use strict;

my $ORACLE_HOME = $ENV{ORACLE_HOME};
my $SQLPLUS = $ENV{SQLPLUS};
if ( $SQLPLUS eq "" )
{
  $SQLPLUS = "$ORACLE_HOME/bin/sqlplus ";
}

my $h ;

sub new
{
  my ($pkg) = @_ ;
  my $self = $pkg->SUPER::new; 
  return $self;
}

sub executeCmd
{
  my $self = shift ;
  my ($cmd) = @_;
  my $ses = $self->{'session'} ;
  if(defined $ses)
  {
    print $ses $cmd."\n" ;
  }
}

sub executeScript
{
  my $self = shift ;
  my ($script) = @_;
  my $ses = $self->{'session'} ;
  if(defined $ses)
  {
    print $ses '@'.$script."\n" ;
  }
}

sub connect
{
  my $self = shift ;
  my $fh = IO::Handle->new();
  my $output = $self->getOutput ;
  if(open($fh,"|$SQLPLUS \"$self->{'user'}/$self->{'password'}\@$self->{'connect_string'}\" $self->{'connect_as'} $output"))
  {
    $self->{'session'} = $fh ;
    return 1;
  }
  return 0;
}

sub disconnect 
{
  my $self = shift ;
  my $fh = $self->{'session'} ;
  close($fh); 
}

sub setOutput
{
  my $self = shift ;
  my ($out) = @_ ;
  $self->{'output'} = $out ;
}

sub getOutput
{
  my $self = shift ;
  my $out = $self->{'output'} ;
  if(defined $out)
  {
    return $out ;
  }else
  {
    return "> /dev/null";
  }  
}

sub setConnectAs
{
  my $self = shift ;
  my ($connAs) = @_;
  $self->{'connect_as'} = $connAs ;
}

sub setConnectString
{
  my $self = shift ;
  my ($connStr) = @_;
  $self->{'connect_string'} = $connStr ;
}

sub setUser
{
  my $self = shift ;
  my ($user) = @_;
  $self->{'user'} = $user ;
}

sub setPassword
{
  my $self = shift ;
  my ($pass) = @_;
  $self->{'password'} = $pass ;
}

sub setConnectInfo
{
  my $self = shift ;
  my ($host,$port,$sid) = @_;
  $self->setConnectString("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=$host)(Port=$port))(CONNECT_DATA=(SID=$sid)))");
}
1;
