Mojolicious::Plugin::PgAsync - Mojolicious Plugin for asynchronous operation with PostgreSQL
# 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}); } );
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.
Mojolicious::Plugin::PgAsync contains two helpers: pg and pg_listen.
pg
pg_listen
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.
dbh
sth
$self->pg('UPDATE test SET name=?', undef, 'foo', sub { my $db = shift; my $rv = $db->sth->rows; $db->dbh->commit if $rv == 1; } );
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.
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.
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; }, ); };
Alexander Romanenko romanenko@cpan.org
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.
To install Mojolicious::Plugin::PgAsync, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Mojolicious::Plugin::PgAsync
CPAN shell
perl -MCPAN -e shell install Mojolicious::Plugin::PgAsync
For more information on module installation, please visit the detailed CPAN module installation guide.