############################################################################
##      Copyright (C) 2005 Subredu Manuel                                  #
##      Author Subredu Manuel <diablo@iasi.roedu.net>                      #
##                                                                         #
## This program is free software; you can redistribute it and/or modify    #
## it under the terms of the GNU General Public License as published by    #
## the Free Software Foundation; either version 2 of the License, or       #
## (at your option) any later version.                                     #
##                                                                         #
## This program is distributed in the hope that it will be useful,         #
## but WITHOUT ANY WARRANTY; without even the implied warranty of          #
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
## GNU General Public License for more details.                            #
##                                                                         #
## You should have received a copy of the GNU General Public License       #
## along with this program; if not, write to the Free Software             #
## Foundation, Inc., 59 Temple Place - Suite 330, Boston,                  #
## MA 02111-1307,USA.                                                      #
############################################################################

package RoPkg::DB;

use warnings;
use strict;

use Class::Singleton;
use DBI;
use Scalar::Util qw(blessed);
use English      qw( -no_match_vars );

use RoPkg::Exceptions;
use RoPkg::Utils qw(CheckParam);

use vars qw($VERSION);
use base qw(Class::Singleton);

$VERSION = '0.1.12';

sub new {
  shift;
  return RoPkg::DB->instance(@_);
}

sub _new_instance {
  my ($class, %opt) = @_;
  my $self;

  $self = bless { %opt }, $class;
  $self->{conn} = ();
  return $self;
}

sub Add {
  my ($self, $dsn, $dbuser, $dbpass, $name) = @_;
  my $dbh;
  my %db;

  if ( !blessed($self)) {
    OutsideClass->throw(
      error    => 'Called outside class instance',
      pkg_name => 'RoPkg::DB',
    );
  }
  
  $db{dsn}    = $dsn;
  $db{dbuser} = $dbuser;
  $db{dbpass} = $dbpass;
  $db{name}   = $name;

  CheckParam(\%db, qw(dsn dbuser name));

  if ( exists $self->{conn}->{$name} ) {
    DB::ConnExists->throw(error => "Connection $name already exists",
        dsn => $dsn,
        user => $dbuser,
        pass =>'***not-shown***');
  }

  $dbh = DBI->connect_cached($dsn, $dbuser, $dbpass, { RaiseError => 0, PrintError => 0 });
  if ( !$dbh ) {
    DB::Connect->throw(DBI::errstr);
  }

  $self->_set_dbh_defaults($dbh);
  
  $db{dbh}  = $dbh;
  $self->{conn}->{$name} = \%db;

  $self->_create_db_method($name);

  return 1;
}

sub _set_dbh_defaults {
  my ($self, $dbh) = @_;
  
  $dbh->{HandleError} = sub {
    DB->throw($_[0]);
  };

  # we set the error handle. Now is time to start throwing exceptions all around ;)
  $dbh->{RaiseError} = 1;
  $dbh->{PrintError} = 0;

  return 1;
}

sub _create_db_method {
  my ($self, $name) = @_;
  
  no strict 'refs';
  *{'RoPkg::DB::db_' . $name} = sub {
                                my ($self) = @_;
                                return $self->_reconnect($name);
  };
  use strict;

  return 1;
}

sub Del {
  my ($self, $name) = @_;

  if ( !blessed($self)) {
    OutsideClass->throw('Called outside class');
  }
  if (! exists $self->{conn}->{$name}) {
    DB::ConnNotFound->throw("Connection $name not found");
  }

  $self->{conn}->{$name}->{dbh}->disconnect;
  return delete $self->{conn}->{$name};
}

sub Has {
  my ($self, $name) = @_;

  if ( !blessed($self)) {
    OutsideClass->throw('Called outside class');
  }

  if ( !$name ) {
    Param::Missing->throw('name of the connection has not been specified');
  }

  return 0 if (! exists $self->{conn}->{$name});
  return 1;
}

sub Reconnect {
  my ($self, $name) = @_;
  my $dbh;
  my %db;

  if ( !blessed($self)) {
    OutsideClass->throw('Called outside class instance');
  }

  if ( !$name ) {
    Param::Missing->throw('Connection name has not been specified');
  }

  if (( defined $name) && (! exists $self->{conn}->{$name})) {
    DB::ConnNotFound->throw(error => "Connection $name does not exists",
        dsn => $self->{conn}->{$name}->{dsn},
        user => $self->{conn}->{$name}->{dbuser},
        pass =>'***not-shown***');
  }

  if (defined $name) {
    $self->_reconnect($name);
  } else {
    foreach(keys %{ $self->{conn} }) {
      $self->_reconnect($_);
    }
  }

  return 1;
}

sub _reconnect {
  my ($self, $name) = @_;
  my $conn_info;
  
  $conn_info = $self->{conn}->{$name};

  eval {
    $conn_info->{dbh} = DBI->connect_cached(
                            $conn_info->{dsn},
                            $conn_info->{dbuser},
                            $conn_info->{dbpass}, {
                              RaiseError => 1,
                              PrintError => 0,
                            }
                           );
  };

  if ( Exception::Class->caught('DB') ) {
    DB->Connect->throw($EVAL_ERROR->message);
  } else {
    die $EVAL_ERROR->message if (ref $EVAL_ERROR);
  }

  return $conn_info->{dbh};
}

sub TableExists {
  my ($self, $name, $table) = @_;

  if ( !blessed($self)) {
    OutsideClass->throw('Call from outside class instance');
  }

  if ( !$name ) {
    Param::Missing->throw('Connection name has not been specified');
  }

  if ( !$table ) {
    Param::Missing->throw('Table name has not been specified');
  }

  if ( ! $self->Has($name) ) {
    DB::ConnNotFound->throw("Connection $name not found");
  }

  return 0 if (! defined $table);

  eval {
    $self->{conn}->{$name}->{dbh}->do(qq{SELECT * FROM $table WHERE 1=0});
  };

  return 0 if ( Exception::Class->caught('DB') );
  die $EVAL_ERROR if (ref $EVAL_ERROR);

  return 1;
}

1;

__END__

=head1 NAME

RoPkg::DB - A Singleton database pool class

=head1 VERSION

0.1.12

=head1 DESCRIPTION

RoPkg::DB is a database pool class. Using this class you can
have access to multiple databases (no matter what kind of 
database), from a single object. RoPkg::DB is ideal in 
persistent environments because at base, is a singleton
class. This class is intensively used by Simba but it
can be used in any other project.

=head1 SYNOPSIS

 use RoPkg::DB;
 
 sub main {
   my $dbp = new RoPkg::DB();
 
   eval {
     $dbp->Add('dbi:mysql:database=mysql;host=localhost',
               'root',
               '',
               'local');
     $dbp->Add('dbi:mysql:database=somedb;host=somehost',
               'username',
               'mypass',
               'somedb');
   };
 
   die($@->package . ' said: ' . $@->message) if ref($@);
 
   print 'Conn to localhost is:',$dbp->db_local,$/,
         'Conn to remote is:',$dbp->db_somedb,$/;
  
   $dbp->Del('somedb');
 
 }

=head1 SUBROUTINES/METHODS

All methods (besides new), raise OutsideClass exception
when are not called within a class instance. Also, each
method may raise diferent exceptions from one case
to another. Please read the documentation for each
method to find out what are the exceptions raised by 
each method.

=head2 new()

new is the contructor of the class. It does not do anything.

=head2 Add($dsn, $dbuser, $dbpass, $conn_name)

add and initialize a new connection to the pool. $dsn must
be in the DBI format. $dsn and $dbpass are the username
and password used to connect to the database. $conn_name
is the method who will be used to access the database handle.
Please note that the method that will be created will be 
prefixed with "db_" .

Example:

 $dbp->Add('dbi:mysql:database=mysql;host=localhost','root',q{},'local');

The method that will be used to get the database handle for this connection
is db_local . 

Add() may raise the following exceptions:

=over 3

=item *) Param::Missing

=item *) DB::ConnExists

=item *) DB::Connect

=back

I<Param::Missing> is raised when $dsn, $dbuser or $conn_name 
are not defined. I<DB::ConnExists> is raised when a connection
with the name $conn_name already exists. I<DB::Connect>
is raised when the connection with the database could not
be established. Besides this exceptions, each database handler
has RaiseError set to 1 and PrintError set to 0. Also, when
errors occurs, DBI will raise a I<DB> exception. The
method always returns 1.

=head2 Del($name)

removes the connection named $name from the pool. The
connection is closed first in a civilised manner. If the
connection $name is not found, DB::ConnNotFound is raised.

=head2 Has($name)

Returns 0 if the connection named $name does not exists,
1 otherwise. Param::Missing exception is raised if
$name is not defined.

=head2 Reconnect($name)

Force a reconnect of the connection named $name. If $name
is not defined, Param::Missing is raised. If a connection
named $name does not exists, DB::ConnNotFound is raised.
This method always returns 1.

=head2 TableExists($name, $table_name)

Returns 1 if the table $table_name exists in the database
specified by the connection named $name, 0 otherwise. If
$name or $table_name parameters are not defined, a
Param::Missing exception is raised. If the connection
$name does not exists, DB::ConnNotFound is raised.

=head1 DEPENDENCIES

RoPkg::DB requires perl 5.008 or later and the following modules:

=over 4

=item RoPkg >= 0.4.4

=item DBI

=item Class::Singleton

=item English

=back

=head1 DIAGNOSTICS

This module comes with tests. To run the tests, unpack the source
and run 'make test'

=head1 PERL CRITIC

This module is perl critic level 2 compliant (with 1 exception)

=head1 CONFIGURATION AND ENVIRONMENT

This module does not use any configuration files or environment
variables. The used modules however may use such things. Please
refer to each module man page for more information.

=head1 INCOMPATIBILITIES

None known to the author

=head1 BUGS AND LIMITATIONS

None known to the author

=head1 SEE ALSO

L<RoPkg::DBObject> L<RoPkg::Exceptions> L<RoPkg::Utils>

=head1 AUTHOR

Subredu Manuel <diablo@iasi.roedu.net>

=head1 LICENSE AND COPYRIGHT

Copyright (C) 2005 Subredu Manuel.  All Rights Reserved.
This module is free software; you can redistribute it 
and/or modify it under the same terms as Perl itself.
The LICENSE file contains the full text of the license.

=cut
