test79.cxx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <cerrno>
  2. #include <cstring>
  3. #include <iostream>
  4. #include <pqxx/notification>
  5. #include <pqxx/transaction>
  6. #include <pqxx/transactor>
  7. #include "test_helpers.hxx"
  8. // Example program for libpqxx. Test waiting for notification with timeout.
  9. namespace
  10. {
  11. // Sample implementation of notification receiver.
  12. class TestListener final : public pqxx::notification_receiver
  13. {
  14. bool m_done;
  15. public:
  16. explicit TestListener(pqxx::connection &conn, std::string const &Name) :
  17. pqxx::notification_receiver(conn, Name), m_done(false)
  18. {}
  19. void operator()(std::string const &, int be_pid) override
  20. {
  21. m_done = true;
  22. PQXX_CHECK_EQUAL(
  23. be_pid, conn().backendpid(), "Notification came from wrong backend.");
  24. std::cout << "Received notification: " << channel() << " pid=" << be_pid
  25. << std::endl;
  26. }
  27. bool done() const { return m_done; }
  28. };
  29. void test_079()
  30. {
  31. pqxx::connection conn;
  32. std::string const NotifName{"mylistener"};
  33. TestListener L(conn, NotifName);
  34. // First see if the timeout really works: we're not expecting any notifs
  35. int notifs{conn.await_notification(0, 1)};
  36. PQXX_CHECK_EQUAL(notifs, 0, "Got unexpected notification.");
  37. pqxx::perform([&conn, &L] {
  38. pqxx::work tx{conn};
  39. tx.exec0("NOTIFY " + L.channel());
  40. tx.commit();
  41. });
  42. for (int i{0}; (i < 20) and not L.done(); ++i)
  43. {
  44. PQXX_CHECK_EQUAL(notifs, 0, "Got notifications, but no handler called.");
  45. std::cout << ".";
  46. notifs = conn.await_notification(1, 0);
  47. }
  48. std::cout << std::endl;
  49. PQXX_CHECK(L.done(), "No notifications received.");
  50. PQXX_CHECK_EQUAL(notifs, 1, "Got unexpected notifications.");
  51. }
  52. } // namespace
  53. PQXX_REGISTER_TEST(test_079);