test30.cxx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <iostream>
  4. #include <pqxx/transaction>
  5. #include "test_helpers.hxx"
  6. using namespace pqxx;
  7. // Test program for libpqxx. Query a table and report its metadata.
  8. namespace
  9. {
  10. void test_030()
  11. {
  12. std::string const Table{"pg_tables"};
  13. connection conn;
  14. work tx{conn, "test30"};
  15. result R(tx.exec(("SELECT * FROM " + Table).c_str()));
  16. PQXX_CHECK(not std::empty(R), "Table " + Table + " is empty, cannot test.");
  17. // Print column names
  18. for (pqxx::row::size_type c{0}; c < R.columns(); ++c)
  19. {
  20. std::string N{R.column_name(c)};
  21. PQXX_CHECK_EQUAL(
  22. R[0].column_number(N), R.column_number(N),
  23. "row::column_number() is inconsistent with result::column_number().");
  24. PQXX_CHECK_EQUAL(R[0].column_number(N), c, "Inconsistent column numbers.");
  25. }
  26. // If there are rows in R, compare their metadata to R's.
  27. if (std::empty(R))
  28. {
  29. std::cout << "(Table is empty.)\n";
  30. return;
  31. }
  32. PQXX_CHECK_EQUAL(R[0].rownumber(), 0, "Row 0 reports wrong number.");
  33. if (std::size(R) < 2)
  34. std::cout << "(Only one row in table.)\n";
  35. else
  36. PQXX_CHECK_EQUAL(R[1].rownumber(), 1, "Row 1 reports wrong number.");
  37. for (pqxx::row::size_type c{0}; c < std::size(R[0]); ++c)
  38. {
  39. std::string N{R.column_name(c)};
  40. PQXX_CHECK_EQUAL(
  41. std::string{R[0].at(c).c_str()}, R[0].at(N).c_str(),
  42. "Different field values by name and by number.");
  43. PQXX_CHECK_EQUAL(
  44. std::string{R[0][c].c_str()}, R[0][N].c_str(),
  45. "at() is inconsistent with operator[].");
  46. PQXX_CHECK_EQUAL(R[0][c].name(), N, "Inconsistent field names.");
  47. PQXX_CHECK_EQUAL(
  48. std::size(R[0][c]), std::strlen(R[0][c].c_str()),
  49. "Inconsistent field lengths.");
  50. }
  51. }
  52. PQXX_REGISTER_TEST(test_030);
  53. } // namespace