test_transaction.cxx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #include <pqxx/nontransaction>
  2. #include <pqxx/robusttransaction>
  3. #include "../test_helpers.hxx"
  4. namespace
  5. {
  6. void test_nontransaction_continues_after_error()
  7. {
  8. pqxx::connection c;
  9. pqxx::nontransaction tx{c};
  10. PQXX_CHECK_EQUAL(
  11. tx.query_value<int>("SELECT 9"), 9, "Simple query went wrong.");
  12. PQXX_CHECK_THROWS(
  13. tx.exec("SELECT 1/0"), pqxx::sql_error, "Expected error did not happen.");
  14. PQXX_CHECK_EQUAL(
  15. tx.query_value<int>("SELECT 5"), 5, "Wrong result after error.");
  16. }
  17. std::string const table{"pqxx_test_transaction"};
  18. void delete_temp_table(pqxx::transaction_base &tx)
  19. {
  20. tx.exec0(std::string{"DROP TABLE IF EXISTS "} + table);
  21. }
  22. void create_temp_table(pqxx::transaction_base &tx)
  23. {
  24. tx.exec0("CREATE TEMP TABLE " + table + " (x integer)");
  25. }
  26. void insert_temp_table(pqxx::transaction_base &tx, int value)
  27. {
  28. tx.exec0(
  29. "INSERT INTO " + table + " (x) VALUES (" + pqxx::to_string(value) + ")");
  30. }
  31. int count_temp_table(pqxx::transaction_base &tx)
  32. {
  33. return tx.query_value<int>("SELECT count(*) FROM " + table);
  34. }
  35. void test_nontransaction_autocommits()
  36. {
  37. pqxx::connection c;
  38. pqxx::nontransaction tx1{c};
  39. delete_temp_table(tx1);
  40. create_temp_table(tx1);
  41. tx1.commit();
  42. pqxx::nontransaction tx2{c};
  43. insert_temp_table(tx2, 4);
  44. tx2.abort();
  45. pqxx::nontransaction tx3{c};
  46. PQXX_CHECK_EQUAL(
  47. count_temp_table(tx3), 1,
  48. "Did not keep effect of aborted nontransaction.");
  49. delete_temp_table(tx3);
  50. }
  51. template<typename TX> void test_double_close()
  52. {
  53. pqxx::connection c;
  54. TX tx1{c};
  55. tx1.exec1("SELECT 1");
  56. tx1.commit();
  57. tx1.commit();
  58. TX tx2{c};
  59. tx2.exec1("SELECT 2");
  60. tx2.abort();
  61. tx2.abort();
  62. TX tx3{c};
  63. tx3.exec1("SELECT 3");
  64. tx3.commit();
  65. PQXX_CHECK_THROWS(
  66. tx3.abort(), pqxx::usage_error, "Abort after commit not caught.");
  67. ;
  68. TX tx4{c};
  69. tx4.exec1("SELECT 4");
  70. tx4.abort();
  71. PQXX_CHECK_THROWS(
  72. tx4.commit(), pqxx::usage_error, "Commit after abort not caught.");
  73. }
  74. void test_transaction()
  75. {
  76. test_nontransaction_continues_after_error();
  77. test_nontransaction_autocommits();
  78. test_double_close<pqxx::transaction<>>();
  79. test_double_close<pqxx::read_transaction>();
  80. test_double_close<pqxx::nontransaction>();
  81. test_double_close<pqxx::robusttransaction<>>();
  82. }
  83. PQXX_REGISTER_TEST(test_transaction);
  84. } // namespace