Skip to content

Instantly share code, notes, and snippets.

@brianmed
Last active April 1, 2020 02:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianmed/8590672 to your computer and use it in GitHub Desktop.
Save brianmed/8590672 to your computer and use it in GitHub Desktop.
Non-blocking DBD::Pg attempt
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