dbi-reconnect.txt

=head1 METHODS

=head2 execute_or_reconnect($sql, @data)

Returns reference to a statement handle object on success and empty list
on failure. Check C<$@> for error message.

Example:

 my $sth;

 while(1) {
     $sth = $dbh->execute_or_reconnect("SELECT * from MyTable") and last;
     warn "Something went wrong: $@";
     sleep 1;
 }

=cut

*DBI::execute_or_reconnect = sub {
    my $dbh = shift;
    my $sql = shift;
    my @data = @_;

    local $dbh->{'HandleError'} = sub {
        my $err = shift;

        local $dbh->{'HandleError'}; # make it die on second try

        if($err =~ /disconnect/) {
            $dbh->{'dbi_connect_closure'}->();
        }
        else {
            die $err;
        }
    };

    return eval { my $sth = $dbh->prepare($sql); $sth->execute(@data) }
};