From 6790782acfdd99e0890ea031f547afc9146cd50c Mon Sep 17 00:00:00 2001 From: barnold Date: Thu, 15 Sep 2022 21:06:00 +0100 Subject: [PATCH] Add some db resilience... Replace the dbh attribute with a get_dbh method. The method checks whether the connection is good before returning it. --- lib/MyModel.pm | 28 ++++++++++++++++------------ lib/MyModel/Book.pm | 2 +- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/lib/MyModel.pm b/lib/MyModel.pm index 537a1c2..3a6adb4 100644 --- a/lib/MyModel.pm +++ b/lib/MyModel.pm @@ -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; } diff --git a/lib/MyModel/Book.pm b/lib/MyModel/Book.pm index 3d911a0..fc0262d 100644 --- a/lib/MyModel/Book.pm +++ b/lib/MyModel/Book.pm @@ -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;