test02.cxx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <pqxx/transaction>
  2. #include "test_helpers.hxx"
  3. using namespace pqxx;
  4. // Example/test program for libpqxx. Perform a query and enumerate its output
  5. // using array indexing.
  6. namespace
  7. {
  8. void bad_connect()
  9. {
  10. connection conn{"totally#invalid@connect$string!?"};
  11. }
  12. void test_002()
  13. {
  14. // Before we really connect, test the expected behaviour of the default
  15. // connection type, where a failure to connect results in an immediate
  16. // exception rather than a silent retry.
  17. PQXX_CHECK_THROWS_EXCEPTION(
  18. bad_connect(), "Invalid connection string did not cause exception.");
  19. // Set up connection to database
  20. std::string ConnectString;
  21. connection C{ConnectString};
  22. // Start transaction within context of connection.
  23. work T{C, "test2"};
  24. // Perform query within transaction.
  25. result R(T.exec("SELECT * FROM pg_tables"));
  26. // Let's keep the database waiting as briefly as possible: commit now,
  27. // before we start processing results. We could do this later, or since
  28. // we're not making any changes in the database that need to be committed,
  29. // we could in this case even omit it altogether.
  30. T.commit();
  31. // Ah, this version of postgres will tell you which table a column in a
  32. // result came from. Let's just test that functionality...
  33. oid const rtable{R.column_table(0)};
  34. PQXX_CHECK_EQUAL(
  35. rtable, R.column_table(pqxx::row::size_type(0)),
  36. "Inconsistent answers from column_table()");
  37. std::string const rcol{R.column_name(0)};
  38. oid const crtable{R.column_table(rcol)};
  39. PQXX_CHECK_EQUAL(
  40. crtable, rtable, "Field looked up by name gives different origin.");
  41. // Now we've got all that settled, let's process our results.
  42. for (auto const &f : R)
  43. {
  44. oid const ftable{f[0].table()};
  45. PQXX_CHECK_EQUAL(ftable, rtable, "field::table() is broken.");
  46. oid const ttable{f.column_table(0)};
  47. PQXX_CHECK_EQUAL(
  48. ttable, f.column_table(pqxx::row::size_type(0)),
  49. "Inconsistent pqxx::row::column_table().");
  50. PQXX_CHECK_EQUAL(ttable, rtable, "Inconsistent result::column_table().");
  51. oid const cttable{f.column_table(rcol)};
  52. PQXX_CHECK_EQUAL(cttable, rtable, "pqxx::row::column_table() is broken.");
  53. }
  54. }
  55. PQXX_REGISTER_TEST(test_002);
  56. } // namespace