2
0

test32.cxx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <pqxx/nontransaction>
  2. #include <pqxx/transaction>
  3. #include <pqxx/transactor>
  4. #include "test_helpers.hxx"
  5. using namespace pqxx;
  6. // Test program for libpqxx. Verify abort behaviour of transactor.
  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. //
  11. // Note for the superstitious: the numbering for this test program is pure
  12. // coincidence.
  13. namespace
  14. {
  15. // Let's take a boring year that is not going to be in the "pqxxevents" table
  16. constexpr int BoringYear{1977};
  17. std::pair<int, int> count_events(connection &conn, std::string const &table)
  18. {
  19. std::string const count_query{"SELECT count(*) FROM " + table};
  20. work tx{conn};
  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_032()
  28. {
  29. connection conn;
  30. {
  31. nontransaction tx{conn};
  32. test::create_pqxxevents(tx);
  33. }
  34. std::string const Table{"pqxxevents"};
  35. std::pair<int, int> const Before{
  36. perform([&conn, &Table] { return count_events(conn, Table); })};
  37. PQXX_CHECK_EQUAL(
  38. Before.second, 0,
  39. "Already have event for " + to_string(BoringYear) + ", cannot test.");
  40. {
  41. quiet_errorhandler d(conn);
  42. PQXX_CHECK_THROWS(
  43. perform([&conn, &Table] {
  44. work{conn}.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. std::pair<int, int> const After{
  54. perform([&conn, &Table] { return count_events(conn, Table); })};
  55. PQXX_CHECK_EQUAL(After.first, Before.first, "Event count changed.");
  56. PQXX_CHECK_EQUAL(
  57. After.second, Before.second,
  58. "Event count for " + to_string(BoringYear) + " changed.");
  59. }
  60. PQXX_REGISTER_TEST(test_032);
  61. } // namespace