test18.cxx 2.1 KB

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