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;
|
package MyModel;
|
||||||
use feature qw( signatures );
|
use feature qw( signatures );
|
||||||
use Moose;
|
use Moose;
|
||||||
|
use Mojo::Log;
|
||||||
no warnings qw( experimental::signatures );
|
no warnings qw( experimental::signatures );
|
||||||
|
|
||||||
|
our $logger = Mojo::Log->new;
|
||||||
|
|
||||||
# Share this among all model instances.
|
# Share this among all model instances.
|
||||||
our $dbh;
|
our $dbh;
|
||||||
|
|
||||||
has dbh => (
|
|
||||||
is => 'ro',
|
|
||||||
isa => 'DBI::db',
|
|
||||||
required => 1,
|
|
||||||
lazy => 1,
|
|
||||||
builder => '_build_dbh',
|
|
||||||
);
|
|
||||||
|
|
||||||
sub _build_dbh ($self) {
|
sub _build_dbh ($self) {
|
||||||
|
$dbh = DBI->connect(
|
||||||
|
"dbi:Pg:", '', '',
|
||||||
|
{ AutoCommit => 0, RaiseError => 1, PrintError => 0 },
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub get_dbh ($self) {
|
||||||
if (!defined $dbh) {
|
if (!defined $dbh) {
|
||||||
$dbh = DBI->connect(
|
$logger->info("Establishing database connection.");
|
||||||
"dbi:Pg:", '', '',
|
$self->_build_dbh;
|
||||||
{ AutoCommit => 0, RaiseError => 1, PrintError => 0 },
|
} elsif (!$dbh->ping) {
|
||||||
);
|
$logger->warn("Database connection lost, reconnecting.");
|
||||||
|
$self->_build_dbh;
|
||||||
}
|
}
|
||||||
return $dbh;
|
return $dbh;
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,7 +5,7 @@ extends 'MyModel';
|
||||||
no warnings qw( experimental::signatures );
|
no warnings qw( experimental::signatures );
|
||||||
|
|
||||||
sub count_all ($self) {
|
sub count_all ($self) {
|
||||||
my ($book_count) = $self->dbh->selectrow_array(
|
my ($book_count) = $self->get_dbh->selectrow_array(
|
||||||
'SELECT COUNT(*) FROM book'
|
'SELECT COUNT(*) FROM book'
|
||||||
);
|
);
|
||||||
return $book_count;
|
return $book_count;
|
||||||
|
|
Loading…
Reference in New Issue