NAME
Mojolicious::Plugin::PgAsync - Mojolicious Plugin for asynchronous operation with PostgreSQL
SYNOPSIS
# Mojolicious::Lite
plugin PgAsync => {dbi => ['dbi:Pg:dbname=test', 'postgres', '', {AutoCommit => 1, RaiseError => 1}]};
# in controller
$self->pg('SELECT 3 as id, pg_sleep(?)', undef, 3,
sub {
my $db = shift;
my $info = $db->sth->fetchall_arrayref({});
$self->render(text => $info->[0]{id});
}
);
DESCRIPTION
Mojolicious::Plugin::PgAsync is a plugin for Mojolicious apps for asynchronous operation (non-blocking) with PostgreSQL using DBD::Pg, include listen feature. Plugin uses own connections pool.
HELPERS
Mojolicious::Plugin::PgAsync contains two helpers: pg
and pg_listen
.
pg
Like DBI method do or selectall_arrayref execute a single statement. Callback return object Mojolicious::Plugin::PgAsync::Db contains methods dbh
and sth
for fetch result or commit transaction.
$self->pg('UPDATE test SET name=?', undef, 'foo',
sub {
my $db = shift;
my $rv = $db->sth->rows;
$db->dbh->commit if $rv == 1;
}
);
pg_listen
Listen for a notification.
$self->pg_listen('foo', sub {
my $notify = shift;
$self->render(text => 'channel '.$notify->{channel});
});
Callback return hashref with keys channel(alias name), pid and payload.
ATTRIBUTES
Mojolicious::Plugin::PgAsync contains the following attributes:
dbi
Arrayref of DBI parameters for connect to PostgreSQL DB.
ttl
Time to life for idle connections, seconds. Default - 30.
EXAMPLE
After 2 seconds print listen foo bar
plugin PgAsync => {dbi => ['dbi:Pg:dbname=test', 'postgres', '', {AutoCommit => 0, RaiseError => 1}]};
get '/listen' => sub {
my $self = shift->render_later;
Mojo::IOLoop->delay(
sub {
my $delay = shift;
$self->pg_listen('foo', $delay->begin);
$self->pg_listen('bar', $delay->begin);
},
sub {
my $delay = shift;
my($notify1, $notify2) = @_;
$self->render(text => "listen $notify1->{name} $notify2->{name}");
},
);
Mojo::IOLoop->delay(
sub {
my $delay = shift;
Mojo::IOLoop->timer(2 => $delay->begin);
},
sub {
my $delay = shift;
$self->pg(q/SELECT pg_notify('foo')/, $delay->begin);
$self->pg(q/SELECT pg_notify('bar')/, $delay->begin);
},
sub {
my $delay = shift;
my($db1, $db2) = @_;
$db1->dbh->commit;
$db2->dbh->commit;
},
);
};
AUTHOR
Alexander Romanenko romanenko@cpan.org
COPYRIGHT & LICENSE
Copyright (C) 2013 by Alexander Romanenko.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.