| 1 | package Mojolicious::Plugin::PgAsync::Db; | ||
| 2 | use Mojo::Base 'Mojo::EventEmitter'; | ||
| 3 | |||
| 4 | use IO::Handle; | ||
| 5 | use DBD::Pg ':async'; | ||
| 6 | use Data::Dumper; | ||
| 7 | |||
| 8 | our $VERSION = '0.01'; | ||
| 9 | |||
| 10 | our $debug = $ENV{DEBUG_PG}; | ||
| 11 | |||
| 12 | has [qw/ dbi sth handle make_free /]; | ||
| 13 | my @class_attr = qw/ callback sql attr values /; | ||
| 14 | has \@class_attr; | ||
| 15 | has ioloop => sub { Mojo::IOLoop->singleton }; | ||
| 16 | has dbh => sub { | ||
| 17 | my $self = shift; | ||
| 18 | my $dbh = DBI->connect(@{$self->dbi}); | ||
| 19 | $self->handle(IO::Handle->new_from_fd($dbh->{pg_socket}, 'r')); | ||
| 20 | |||
| 21 | my $reactor = $self->ioloop->reactor; | ||
| 22 | $reactor->io($self->handle => | ||
| 23 | sub { | ||
| 24 | my $reactor = shift; | ||
| 25 | |||
| 26 | unless ($self->sth) { | ||
| 27 | if (my $notify = $dbh->pg_notifies) { | ||
| 28 | my $notify_hash = { | ||
| 29 | name => $notify->[0], | ||
| 30 | channel => $notify->[0], | ||
| 31 | pid => $notify->[1], | ||
| 32 | payload => $notify->[2], | ||
| 33 | }; | ||
| 34 | $self->callback->($notify_hash, $notify_hash); | ||
| 35 | } | ||
| 36 | else { | ||
| 37 | $self->callback->(); | ||
| 38 | } | ||
| 39 | } | ||
| 40 | else { | ||
| 41 | my $result = $self->sth->pg_result; | ||
| 42 | say "result $self $result" if $debug; | ||
| 43 | $self->callback->($self, $self); | ||
| 44 | } | ||
| 45 | |||
| 46 | # Clear class attributes | ||
| 47 | $self->$_(undef) for @class_attr; | ||
| 48 | |||
| 49 | $self->make_free->($self); | ||
| 50 | } | ||
| 51 | )->watch($self->handle, 1, 0); | ||
| 52 | |||
| 53 | return $dbh | ||
| 54 | }; | ||
| 55 | |||
| 56 | sub execute { | ||
| 57 | my $self = shift; | ||
| 58 | my @values = @{$_[0]}; | ||
| 59 | |||
| 60 | $self->attr({%{$self->attr || {}}, pg_async => PG_ASYNC}); | ||
| 61 | |||
| 62 | say "execute $self" if $debug; | ||
| 63 | $self->sth($self->dbh->prepare($self->sql, $self->attr)); | ||
| 64 | $self->sth->execute(@values); | ||
| 65 | |||
| 66 | return $self | ||
| 67 | } | ||
| 68 | |||
| 69 | sub listen { | ||
| 70 | my $self = shift; | ||
| 71 | my $channel = shift; | ||
| 72 | |||
| 73 | $self->sth(undef); | ||
| 74 | say "channel $channel" if $debug; | ||
| 75 | $self->dbh->do("LISTEN $channel"); | ||
| 76 | $self->dbh->commit unless $self->dbh->{AutoCommit}; | ||
| 77 | |||
| 78 | return $self | ||
| 79 | } | ||
| 80 | |||
| 81 | sub disconnect { | ||
| 82 | my $self = shift; | ||
| 83 | |||
| 84 | say "disconnect $self" if $debug; | ||
| 85 | $self->ioloop->reactor->remove($self->handle) if $self->ioloop; | ||
| 86 | $self->dbh->disconnect if $self->dbh; | ||
| 87 | } | ||
| 88 | |||
| 89 | 1 | ||
| 90 |