#!/usr/bin/perl

################################################################################
#
# This perl script checks for availability of the Perl modules DBI and
# DBD::mysql using the "current" perl interpreter.
#
# Useful for test environment checking before testing executable perl scripts
# in the MySQL Server distribution.
#
# NOTE: The "shebang" on the first line of this script should always point to
#       /usr/bin/perl, so that we can use this script to check whether or not we
#       support running perl scripts with such a shebang without specifying the
#       perl interpreter on the command line. Such a script is mysqlhotcopy.
#
#       When run as "checkDBI_DBD-mysql.pl" the shebang line will be evaluated
#       and used. When run as "perl checkDBI_DBD-mysql.pl" the shebang line is
#       not used.
#
# NOTE: This script will, if modules are found, try to connect to the test
#       database and update a value in a table called "checkPerl". This table
#       must be created in advance by scripts calling this script, otherwise
#       an error will occur:
#
#         CREATE TABLE checkPerl (id INT, foundModules INT);
#         # Insert the value 1 for "foundModules" to indicate no success.
#         # The value will be updated to 0 in the called perl script if success.
#         INSERT INTO checkPerl VALUES (1, 1);
#
#       The calling script is also responsible for cleaning up after use:
#
#         DROP TABLE checkPerl
#
# See mysql-test/include/have_dbi_dbd-mysql.inc for example use of this script.
# This script should be executable for the user running MTR.
#
################################################################################

BEGIN {
    # By using eval inside BEGIN we can suppress warnings and continue after.
    # We need to catch "Can't locate" as well as "Can't load" errors.
    eval{
        $FOUND_DBI=0;
        $FOUND_DBD_MYSQL=0;

        # Check for DBI module:
        $FOUND_DBI=1 if require DBI;

        # Check for DBD::mysql module
        $FOUND_DBD_MYSQL=1 if require DBD::mysql;
    };
};

if ($FOUND_DBI && $FOUND_DBD_MYSQL) {
    # Connect to the test database in order to report success:
    my $dbh = DBI->connect("dbi:mysql:database=test;mysql_socket=$ENV{'MASTER_MYSOCK'}",
                         'root', '', 
       {
           RaiseError => 1,
           PrintError => 0,
           AutoCommit => 1,
       }
    );

    # Update the value indicating success (0 means success):
    my $sth = $dbh->prepare("UPDATE checkPerl SET foundModules = 0 WHERE id = 1");
    $sth->execute();
    $dbh->disconnect();
}

1;

