Created
January 19, 2013 04:11
-
-
Save rkitover/4570699 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package EMS::DBUtils; | |
use strict; | |
use warnings; | |
use FindBin '$Bin'; | |
use lib "$Bin/perl"; | |
use EMS::Error; | |
use EMS::DB '$db'; | |
use Try::Tiny; | |
# Since this module is used by everything, do some things for the whole app | |
# (when not running in Mojolicious.) | |
BEGIN { | |
unless (exists $INC{'Mojolicious.pm'}) { | |
# show errors on 500s | |
require CGI::Carp; | |
CGI::Carp->import('fatalsToBrowser'); | |
# turn off warnings | |
$SIG{__WARN__} = sub {}; | |
} | |
} | |
our $dbh = bless {}, 'EMS::__FakeDBH'; | |
sub dbConnect | |
{ | |
my $error = try { | |
ping(); undef; | |
} | |
catch { | |
EMS::Error->new('Database connection failure', $_); | |
}; | |
return $error if $error; | |
return $dbh; | |
} | |
sub ping { $db->run(sub { $_->prepare_cached('SELECT 1')->execute }) } | |
{ | |
package EMS::__FakeDBH; | |
use strict; | |
use warnings; | |
use Sub::Install (); | |
use EMS::DB '$db'; | |
use overload | |
'%{}' => sub { $db->run(sub { $_ }) }, | |
fallback => 1; | |
sub AUTOLOAD { | |
use vars '$AUTOLOAD'; | |
(my $method = $AUTOLOAD) =~ s/.*:://; | |
Sub::Install::install_sub({ | |
code => sub { | |
# do a "ping" to make sure we don't run into the situation where a | |
# cached statement exists, but the connection has gone away. | |
EMS::DBUtils::ping(); | |
shift; # ignore $self | |
my @args = @_; | |
return $db->run(sub { $_->$method(@args) }); | |
}, | |
into => __PACKAGE__, | |
as => $method | |
}); | |
goto __PACKAGE__->can($method); | |
} | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment