Skip to content

Commit

Permalink
reconnect after fork
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Mar 30, 2015
1 parent b319b70 commit 0d2333d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,5 +1,6 @@

2.02 2015-03-30
- Improved fork-safety of Mojo::Pg::PubSub.

2.01 2015-03-25
- Fixed bug where Perl would close the DBD::Pg file descriptor unexpectedly.
Expand Down
4 changes: 4 additions & 0 deletions lib/Mojo/Pg/PubSub.pm
Expand Up @@ -25,6 +25,10 @@ sub unlisten {
sub _db {
my $self = shift;

# Fork-safety
$self->{db} and delete($self->{db})->disconnect
unless ($self->{pid} //= $$) eq $$;

return $self->{db} if $self->{db};

my $db = $self->{db} = $self->pg->db;
Expand Down
19 changes: 19 additions & 0 deletions t/pubsub.t
Expand Up @@ -86,4 +86,23 @@ is_deeply \@test, [], 'no messages';
is_deeply \@test, ['works too'], 'right messages';
};

# Fork-safety
$pg = Mojo::Pg->new($ENV{TEST_ONLINE});
@dbhs = @test = ();
$pg->pubsub->on(reconnect => sub { push @dbhs, pop->dbh });
$pg->pubsub->listen(pstest => sub { push @test, pop });
ok $dbhs[0], 'database handle';
ok $dbhs[0]->ping, 'connected';
$pg->pubsub->notify(pstest => 'first');
is_deeply \@test, ['first'], 'right messages';
{
local $$ = -23;
$pg->pubsub->notify(pstest => 'second');
ok $dbhs[1], 'database handle';
ok $dbhs[1]->ping, 'connected';
isnt $dbhs[0], $dbhs[1], 'different database handles';
ok !$dbhs[0]->ping, 'not connected';
is_deeply \@test, ['first', 'second'], 'right messages';
};

done_testing();

0 comments on commit 0d2333d

Please sign in to comment.