test37.cxx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <pqxx/nontransaction>
  2. #include <pqxx/robusttransaction>
  3. #include <pqxx/transactor>
  4. #include "test_helpers.hxx"
  5. using namespace pqxx;
  6. // Test program for libpqxx. Verify abort behaviour of RobustTransaction.
  7. //
  8. // The program will attempt to add an entry to a table called "pqxxevents",
  9. // with a key column called "year"--and then abort the change.
  10. namespace
  11. {
  12. // Let's take a boring year that is not going to be in the "pqxxevents" table
  13. constexpr int BoringYear{1977};
  14. // Count events and specifically events occurring in Boring Year, leaving the
  15. // former count in the result pair's first member, and the latter in second.
  16. std::pair<int, int> count_events(connection &conn, std::string const &table)
  17. {
  18. std::string const count_query{"SELECT count(*) FROM " + table};
  19. nontransaction tx{conn};
  20. return std::make_pair(
  21. tx.query_value<int>(count_query),
  22. tx.query_value<int>(count_query + " WHERE year=" + to_string(BoringYear)));
  23. }
  24. struct deliberate_error : std::exception
  25. {};
  26. void test_037()
  27. {
  28. connection conn;
  29. {
  30. nontransaction tx{conn};
  31. test::create_pqxxevents(tx);
  32. }
  33. std::string const Table{"pqxxevents"};
  34. auto const Before{
  35. perform([&conn, &Table] { return count_events(conn, Table); })};
  36. PQXX_CHECK_EQUAL(
  37. Before.second, 0,
  38. "Already have event for " + to_string(BoringYear) + ", cannot test.");
  39. {
  40. quiet_errorhandler d(conn);
  41. PQXX_CHECK_THROWS(
  42. perform([&conn, &Table] {
  43. robusttransaction<> tx{conn};
  44. tx.exec0(
  45. "INSERT INTO " + Table + " VALUES (" + to_string(BoringYear) +
  46. ", "
  47. "'yawn')");
  48. throw deliberate_error();
  49. }),
  50. deliberate_error,
  51. "Did not get expected exception from failing transactor.");
  52. }
  53. auto const After{
  54. perform([&conn, &Table] { return count_events(conn, Table); })};
  55. PQXX_CHECK_EQUAL(After.first, Before.first, "Number of events changed.");
  56. PQXX_CHECK_EQUAL(
  57. After.second, Before.second,
  58. "Number of events for " + to_string(BoringYear) + " changed.");
  59. }
  60. PQXX_REGISTER_TEST(test_037);
  61. } // namespace