diff --git a/lib/postgrex/notifications.ex b/lib/postgrex/notifications.ex index 982fea50..5008d134 100644 --- a/lib/postgrex/notifications.ex +++ b/lib/postgrex/notifications.ex @@ -280,7 +280,13 @@ defmodule Postgrex.Notifications do if map_size(state.listener_channels[channel]) == 0 do {_, state} = pop_in(state.listener_channels[channel]) - {:query, ~s(UNLISTEN #{quote_channel(channel)}), %{state | from: from}} + if state.connected do + {:query, ~s(UNLISTEN #{quote_channel(channel)}), %{state | from: from}} + else + from && SimpleConnection.reply(from, :ok) + + {:noreply, state} + end else from && SimpleConnection.reply(from, :ok) diff --git a/test/notification_test.exs b/test/notification_test.exs index 243bc5dc..d6ea8f82 100644 --- a/test/notification_test.exs +++ b/test/notification_test.exs @@ -24,19 +24,26 @@ defmodule NotificationTest do end test "does not fail on sync connection with auto reconnect" do - Process.flag(:trap_exit, true) assert {:ok, pid} = PN.start_link(database: "nobody_knows_it", auto_reconnect: true) assert {:eventually, _} = PN.listen(pid, "channel") + assert Process.alive?(pid) end test "does not fail on async connection with auto reconnect" do - Process.flag(:trap_exit, true) - assert {:ok, pid} = PN.start_link(database: "nobody_knows_it", auto_reconnect: true, sync_connect: false) assert {:eventually, _} = PN.listen(pid, "channel") - refute_receive {:EXIT, _, ^pid}, 100 + assert Process.alive?(pid) + end + + test "does not fail on unlisten while disconnected" do + assert {:ok, pid} = + PN.start_link(database: "nobody_knows_it", auto_reconnect: true, sync_connect: false) + + assert {:eventually, ref} = PN.listen(pid, "channel") + assert :ok = PN.unlisten(pid, ref) + assert Process.alive?(pid) end test "listening", context do