2009-08-06
[Perl] Check if DB table exists
Building on the script of yesterday, I have created a subroutine that will create a table if it doesn't exist. It also uses a DB connect retry for up to an hour in cases where the DB is not available.
The input arg's of the sub:
The input arg's of the sub:
- The table name
- The table create definition
sub CheckTables {
my( $tblname, $tbldef ) = @_;
# Connect to DB
my $cont = 0;
my $tries = 0;
my $dbh1;
while( not $cont ) {
$tries++;
eval {
$dbh1 = DBI->connect( "dbi:mysql:database=$dbdb;host=$dbhost;port=$dbport", "$dbuser", "$dbpass" );
};
if( $@ ) {
sleep( 1 );
} else {
$cont++;
}
if( $tries > 3600 ) {
# We have been trying for an hour - give up
print "CheckTables_GIVE_UP\t1\n";
exit;
}
}
my $sql = "show tables like '$tblname'";
my $sth = $dbh1->prepare( $sql );
my $exists = 0;
if( $sth->execute() ) {
while( my $t = $sth->fetchrow_array() ) {
if( $t =~ /^$tblname$/ ) { $exists = 1; }
}
}
# If table didn't exist, create it
if( not $exists ) {
# Attempt to create table
$dbh1->do( $tbldef );
# Check again
$sth = $dbh1->prepare( $sql );
if( $sth->execute() ) {
while( my $t = $sth->fetchrow_array() ) {
if( $t =~ /^$tblname$/ ) { $exists = 1; }
}
}
}
$dbh1->disconnect;
return $exists;
}