test78.cxx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. Send notification to self, using a
  9. // notification name with unusal characters, and without polling.
  10. namespace
  11. {
  12. // Sample implementation of notification receiver.
  13. class TestListener : public pqxx::notification_receiver
  14. {
  15. bool m_done;
  16. public:
  17. explicit TestListener(pqxx::connection &conn, std::string const &Name) :
  18. pqxx::notification_receiver(conn, Name), m_done(false)
  19. {}
  20. void operator()(std::string const &, int be_pid) override
  21. {
  22. m_done = true;
  23. PQXX_CHECK_EQUAL(
  24. be_pid, conn().backendpid(),
  25. "Got notification from wrong backend process.");
  26. std::cout << "Received notification: " << channel() << " pid=" << be_pid
  27. << std::endl;
  28. }
  29. bool done() const { return m_done; }
  30. };
  31. void test_078()
  32. {
  33. pqxx::connection conn;
  34. std::string const NotifName{"my listener"};
  35. TestListener L{conn, NotifName};
  36. pqxx::perform([&conn, &L] {
  37. pqxx::work tx{conn};
  38. tx.exec0("NOTIFY " + tx.quote_name(L.channel()));
  39. tx.commit();
  40. });
  41. int notifs{0};
  42. for (int i{0}; (i < 20) and not L.done(); ++i)
  43. {
  44. PQXX_CHECK_EQUAL(notifs, 0, "Got unexpected notifications.");
  45. std::cout << ".";
  46. notifs = conn.await_notification();
  47. }
  48. std::cout << std::endl;
  49. PQXX_CHECK(L.done(), "No notification received.");
  50. PQXX_CHECK_EQUAL(notifs, 1, "Got unexpected number of notifications.");
  51. }
  52. } // namespace
  53. PQXX_REGISTER_TEST(test_078);