Skip to content

Instantly share code, notes, and snippets.

/close.diff Secret

Created November 13, 2014 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8a674195eb54a737661e to your computer and use it in GitHub Desktop.
Save anonymous/8a674195eb54a737661e to your computer and use it in GitHub Desktop.
diff --git a/lib/Mojo/Pg/Database.pm b/lib/Mojo/Pg/Database.pm
index aa62f2b..d38a9f4 100644
--- a/lib/Mojo/Pg/Database.pm
+++ b/lib/Mojo/Pg/Database.pm
@@ -144,7 +144,7 @@ sub _watch {
$self->{handle} => sub {
my $reactor = shift;
- $self->_notifications;
+ $self->emit('close')->_unwatch unless eval { $self->_notifications; 1 };
return unless (my $waiting = $self->{waiting}) && $dbh->pg_ready;
my ($sth, $cb) = @{shift @$waiting}{qw(sth cb)};
@@ -185,6 +185,16 @@ L<Mojo::Pg>.
L<Mojo::Pg::Database> inherits all events from L<Mojo::EventEmitter> and can
emit the following new ones.
+=head2 close
+
+ $db->on(close => sub {
+ my $db = shift;
+ ...
+ });
+
+Emitted when the database connection gets closed during non-blocking
+operations or while waiting for notifications.
+
=head2 notification
$db->on(notification => sub {
diff --git a/t/database.t b/t/database.t
index 6afaf40..a846a67 100644
--- a/t/database.t
+++ b/t/database.t
@@ -233,6 +233,16 @@ ok $db->listen('foo')->listen('bar')->unlisten('bar')->is_l
'listening';
ok !$db->unlisten('*')->is_listening, 'not listening';
+# Connection close
+ok $db->listen('foo')->is_listening, 'listening';
+my $delay = Mojo::IOLoop->delay;
+$db->on(close => $delay->begin);
+my $pid = $db->query('select pg_backend_pid()')->array->[0];
+$pg->db->query('select pg_terminate_backend(?)', $pid);
+my $id = Mojo::IOLoop->timer(300 => sub { die 'Connection close' });
+$delay->wait;
+Mojo::IOLoop->remove($id);
+
# Blocking error
eval { $pg->db->query('does_not_exist') };
like $@, qr/does_not_exist/, 'right error';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment