# ipdb/cgi-bin/IPDB.pm
# Contains DB-related functions for IPDB
###
# SVN revision info
# $Date$
# SVN revision $Rev$
# Last update by $Author$
###

# Split from CommonWeb.pm 08/13/2004 kdeugau@vianet

package IPDB;

use strict;
use warnings;
use Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

$VERSION	= 1.0;
@ISA		= qw(Exporter);
@EXPORT_OK	= qw(&connectDB &checkDBSanity);

@EXPORT		= (); # Export nothing by default.
%EXPORT_TAGS	= ( ALL => [qw( &connectDB &checkDBSanity )]
		  );

# Creates connection to IPDB.
# Default is a PostgreSQL db;  could be any DBMS with the
# right changes.  MySQL in comments.  Note that some DBMS's don't
# support transactions, this is a Bad Thing!
# Returns a handle to the db.
sub connectDB {
  my $dbh;
  my $DSN = "DBI:Pg:dbname=ipdb";
  my $user = 'ipdb';
  my $pw   = 'ipdbpwd';

# Note that we want to autocommit by default, and we will turn it off locally as necessary.
  $dbh = DBI->connect($DSN, $user, $pw, { AutoCommit => 1 } )
    or return undef if(!$dbh);

  return $dbh;
} # end connectDB

# Quick check to see if the db is responding.  A full integrity
# check will have to be a separate tool to walk the IP allocation trees.
sub checkDBSanity {
  my $dbh = connectDB();

  if (!$dbh) {
    printError("Cannot connect to the database");
  } else {
    # it connects, try a stmt.
    my $sth = $dbh->prepare('select cidr from masterblocks');
    my $err = $sth->execute();

    if ($sth->fetchrow()) {
      # all is well.
      return 1;
    } else {
      printHeader('');
      printError("Connected to the database, but could not execute test statement sth->errstr()");
    }
  }
  # Clean up after ourselves.
  $dbh->disconnect;
} # end checkDBSanity

# Indicates module loaded OK.  Required by Perl.
1;
