Add some db resilience...
Replace the dbh attribute with a get_dbh method. The method checks whether the connection is good before returning it.
This commit is contained in:
parent
cd1b187a58
commit
6790782acf
|
@ -1,25 +1,29 @@
|
|||
package MyModel;
|
||||
use feature qw( signatures );
|
||||
use Moose;
|
||||
use Mojo::Log;
|
||||
no warnings qw( experimental::signatures );
|
||||
|
||||
our $logger = Mojo::Log->new;
|
||||
|
||||
# Share this among all model instances.
|
||||
our $dbh;
|
||||
|
||||
has dbh => (
|
||||
is => 'ro',
|
||||
isa => 'DBI::db',
|
||||
required => 1,
|
||||
lazy => 1,
|
||||
builder => '_build_dbh',
|
||||
);
|
||||
|
||||
sub _build_dbh ($self) {
|
||||
$dbh = DBI->connect(
|
||||
"dbi:Pg:", '', '',
|
||||
{ AutoCommit => 0, RaiseError => 1, PrintError => 0 },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
sub get_dbh ($self) {
|
||||
if (!defined $dbh) {
|
||||
$dbh = DBI->connect(
|
||||
"dbi:Pg:", '', '',
|
||||
{ AutoCommit => 0, RaiseError => 1, PrintError => 0 },
|
||||
);
|
||||
$logger->info("Establishing database connection.");
|
||||
$self->_build_dbh;
|
||||
} elsif (!$dbh->ping) {
|
||||
$logger->warn("Database connection lost, reconnecting.");
|
||||
$self->_build_dbh;
|
||||
}
|
||||
return $dbh;
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@ extends 'MyModel';
|
|||
no warnings qw( experimental::signatures );
|
||||
|
||||
sub count_all ($self) {
|
||||
my ($book_count) = $self->dbh->selectrow_array(
|
||||
my ($book_count) = $self->get_dbh->selectrow_array(
|
||||
'SELECT COUNT(*) FROM book'
|
||||
);
|
||||
return $book_count;
|
||||
|
|
Loading…
Reference in New Issue