#!/bin/env perl

use strict;
use warnings;
use FileHandle;
use DBI;

my $max_child = 3;
my $child = 0;
my $record = 0;

sub LogOn
{
   my $db;
   my ($dbuser, $dbpasswd, $dbname);

   ($dbuser, $dbpasswd) = split(/\//, $ENV{ATASVRCONNECT});

   if ($dbpasswd =~ /\@/) {
       # Remote connection: Extract database name
       ($dbpasswd, $dbname) = split(/[\@]/, $dbpasswd, 2);
       $dbname = 'TNS:' . $dbname;
   }

   ### Connect to database
   $db = DBI->connect($dbname, $dbuser, $dbpasswd, 'Oracle');
   $db->{AutoCommit} = 0;
   $db->{InactiveDestroy} = 1;

   return $db;
}

sub LogOff
{
   my ($db) = @_;

   if ($db) {
      $db->disconnect;
   }
}


sub ProcessData
{
   my ($child, $record, $value) = @_;

   my $pid = fork();          # Fork a new child process
   if ($pid) {                # This is the parent process
      return;
   }
   else {   # this is the child
      my $db = LogOn();
      
      my $lcsr = $db->prepare(<<EOS);
      INSERT INTO jlodewij.yaa (aa) VALUES (?)
EOS
      $lcsr->execute($value);
      $lcsr->finish;
      $db->commit;

      LogOff($db);

      # Don't forget the \n here!! It is essential for the line to be flushed
      print TO_PARENT "CHILD = $child, VALUE = $value, RECORD = $record\n";
      exit;   
   }
}


sub GetRows
{
   my ($db) = @_;
   my $value;
   my @rows;

   my $lcsr = $db->prepare(<<EOS);
   SELECT aa 
     FROM jlodewij.zaa
EOS
   if ($lcsr->execute()) {
      while ($value = $lcsr->fetchrow) {
         push @rows, $value;
      }
   }
   $lcsr->finish;

   return @rows;
}

pipe(FROM_CHILD, TO_PARENT);        # open the communication pipe
autoflush TO_PARENT 1;

my $db = LogOn();
my @rows = GetRows($db);
LogOff($db);

my $value;

foreach $value (@rows) {   
   print "PUMP: $value, RECORD = $record\n";
   $child++;
   $record++;

   ProcessData($child, $record, $value);
   while ($child >= $max_child) {
      my $retval = <FROM_CHILD>;
      print "$retval\n";
      $child--;
   }
}

# Don't stop the program if there are still child processes running
while ($child > 0) { # if there are any child processes
   my $retval = <FROM_CHILD>;
   print "$retval\n";
   $child--;
}

close FROM_CHILD;  
close TO_PARENT;



