test62.cxx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <cstring>
  2. #include <iostream>
  3. #include <pqxx/transaction>
  4. #include "test_helpers.hxx"
  5. using namespace pqxx;
  6. // Example program for libpqxx. Test binary string functionality.
  7. namespace
  8. {
  9. void test_062()
  10. {
  11. connection conn;
  12. work tx{conn};
  13. std::string const TestStr{
  14. "Nasty\n\030Test\n\t String with \200\277 weird bytes "
  15. "\r\0 and Trailer\\\\\0"};
  16. tx.exec0("CREATE TEMP TABLE pqxxbin (binfield bytea)");
  17. std::string const Esc{tx.esc_raw(std::basic_string<std::byte>{
  18. reinterpret_cast<std::byte const *>(std::data(TestStr)),
  19. std::size(TestStr)})};
  20. tx.exec0("INSERT INTO pqxxbin VALUES ('" + Esc + "')");
  21. result R{tx.exec("SELECT * from pqxxbin")};
  22. tx.exec0("DELETE FROM pqxxbin");
  23. auto const B{R.at(0).at(0).as<std::basic_string<std::byte>>()};
  24. PQXX_CHECK(not std::empty(B), "Binary string became empty in conversion.");
  25. PQXX_CHECK_EQUAL(
  26. std::size(B), std::size(TestStr), "Binary string was mangled.");
  27. std::basic_string<std::byte>::const_iterator c;
  28. std::basic_string<std::byte>::size_type i;
  29. for (i = 0, c = std::begin(B); i < std::size(B); ++i, ++c)
  30. {
  31. PQXX_CHECK(c != std::end(B), "Premature end to binary string.");
  32. char const x{TestStr.at(i)}, y{char(B.at(i))}, z{char(std::data(B)[i])};
  33. PQXX_CHECK_EQUAL(
  34. std::string(&x, 1), std::string(&y, 1), "Binary string byte changed.");
  35. PQXX_CHECK_EQUAL(
  36. std::string(&y, 1), std::string(&z, 1),
  37. "Inconsistent byte at offset " + to_string(i) + ".");
  38. }
  39. }
  40. PQXX_REGISTER_TEST(test_062);
  41. } // namespace