#!/usr/bin/perl

################################################################################
## ping_mysql.pl
## Created 03/10/2000
## Author: Ross A. Carlson
## ross@metacraft.com
## Opens a connection to a MySQL server via the Perl DBI interface
## and attempts to connect to the 'test' database. Exits with an
## exit code of 0 for success, 1 for failure. If present, the MySQL
## error message will be printed to STDERR on failure. The MySQL
## server host and port should be the first two command line
## parameters, respectively.
################################################################################

use DBI;
use strict;

################################################################################
## Configuration variables:
my $db = 'test';
my $db_user = 'ass';
my $db_pass = '';
## End configuration
################################################################################

my $db_host = shift @ARGV;
my $db_port = shift @ARGV;

if (! ($db_host && $db_port)) {
	print STDERR "Usage: ping_mysql.pl mysql-server-host mysql-port\n";
	exit (1);
}

## Connect to the database.
my $dbh = DBI->connect ("DBI:mysql:database=$db;host=$db_host;port=$db_port", $db_user, $db_pass, {RaiseError => 0, PrintError => 0});
if (! $dbh) {
	print STDERR "Database connection to $db_host on port $db_port failed: $DBI::errstr\n";
	exit (1);
}

## Send a simple query to list the tables present in the database.
my $query = "SHOW TABLES";

## Prepare the query.
my $sth = $dbh->prepare ($query);
if (! $sth) {
	print STDERR "Query preparation failed: $DBI::errstr\n";
	$dbh->disconnect;
	exit (1);
}

## Execute the query.
my $result = $sth->execute;
if (! $result) {
	print STDERR "Query execution failed: $DBI::errstr\n";
	$dbh->disconnect;
	$sth->finish;
	exit (1);
}

## Close the statement handle.
$sth->finish;

## Close the database connection.
$result = $dbh->disconnect;
if (! $result) {
	print STDERR "Database handle closure failed: $DBI::errstr\n";
	exit (1);
}

## Return success to calling script.
exit (0);
