Last active
April 1, 2020 02:00
-
-
Save brianmed/8590672 to your computer and use it in GitHub Desktop.
Non-blocking DBD::Pg attempt
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
use Mojolicious::Lite; | |
use DBD::Pg ':async'; | |
use DBI; | |
use Creds; | |
use IO::Handle; | |
get '/async' => sub { | |
my $self = shift->render_later; | |
my $dbh = $self->stash->{_dbh} = DBI->connect($Creds::DSN, $Creds::USER, $Creds::PASS, {RaiseError=>1}); | |
my $handle = $self->stash->{_handle} = IO::Handle->new_from_fd($dbh->{pg_socket}, 'r'); | |
my $reactor = Mojo::IOLoop->singleton->reactor; | |
$reactor->io($handle => | |
sub { | |
my $reactor = shift; | |
my $sth = $self->stash->{_sth}; | |
if ($sth->pg_ready) { | |
$sth->pg_result; | |
my @res = $sth->fetchrow_array; | |
if (@res) { | |
$self->render(text => "res: $res[0]"); | |
} | |
else { | |
$self->render(text => "err: " . $sth->errstr); | |
} | |
} | |
} | |
)->watch($handle, 1, 0); | |
my $sth = $self->stash->{_sth} = $dbh->prepare("select count(*) from zip", {pg_async => PG_ASYNC}); | |
$sth->execute; | |
$self->on(finish => sub { | |
my $handle = $self->stash->{_handle}; | |
Mojo::IOLoop->singleton->reactor->remove($handle); | |
}); | |
}; | |
app->start; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment