test_time.cxx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <pqxx/time>
  2. #include <pqxx/transaction>
  3. #include "../test_helpers.hxx"
  4. namespace
  5. {
  6. #if defined(PQXX_HAVE_YEAR_MONTH_DAY)
  7. using namespace std::literals;
  8. void test_date_string_conversion()
  9. {
  10. pqxx::connection conn;
  11. pqxx::work tx{conn};
  12. std::tuple<int, unsigned, unsigned, std::string_view> const conversions[]{
  13. {-542, 1, 1, "0543-01-01 BC"sv},
  14. {-1, 2, 3, "0002-02-03 BC"sv},
  15. {0, 9, 14, "0001-09-14 BC"sv},
  16. {1, 12, 8, "0001-12-08"sv},
  17. {2021, 10, 24, "2021-10-24"sv},
  18. {10191, 8, 30, "10191-08-30"sv},
  19. {-4712, 1, 1, "4713-01-01 BC"sv},
  20. {32767, 12, 31, "32767-12-31"sv},
  21. {2000, 2, 29, "2000-02-29"sv},
  22. {2004, 2, 29, "2004-02-29"sv},
  23. // This one won't work in postgres, but we can test the conversions.
  24. {-32767, 11, 3, "32768-11-03 BC"sv},
  25. };
  26. for (auto const &[y, m, d, text] : conversions)
  27. {
  28. std::chrono::year_month_day const date{
  29. std::chrono::year{y}, std::chrono::month{m}, std::chrono::day{d}};
  30. PQXX_CHECK_EQUAL(
  31. pqxx::to_string(date), text, "Date did not convert right.");
  32. PQXX_CHECK_EQUAL(
  33. pqxx::from_string<std::chrono::year_month_day>(text), date,
  34. "Date did not parse right.");
  35. if (int{date.year()} > -4712)
  36. {
  37. // We can't test this for years before 4713 BC (4712 BCE), because
  38. // postgres doesn't handle earlier years.
  39. PQXX_CHECK_EQUAL(
  40. tx.query_value<std::string>(
  41. "SELECT '" + pqxx::to_string(date) + "'::date"),
  42. text, "Backend interpreted date differently.");
  43. }
  44. }
  45. std::string_view const invalid[]{
  46. ""sv,
  47. "yesterday"sv,
  48. "1981-01"sv,
  49. "2010"sv,
  50. "2010-8-9"sv,
  51. "1900-02-29"sv,
  52. "2021-02-29"sv,
  53. "2000-11-29-3"sv,
  54. "1900-02-29"sv,
  55. "2003-02-29"sv,
  56. "12-12-12"sv,
  57. "0000-09-16"sv,
  58. "-01-01"sv,
  59. "-1000-01-01"sv,
  60. "1000-00-01"sv,
  61. "1000-01-00"sv,
  62. "2001y-01-01"sv,
  63. "10-09-08"sv,
  64. "0-01-01"sv,
  65. "0000-01-01"sv,
  66. "2021-13-01"sv,
  67. "2021-+02-01"sv,
  68. "2021-12-32"sv,
  69. };
  70. for (auto const text : invalid)
  71. PQXX_CHECK_THROWS(
  72. pqxx::ignore_unused(
  73. pqxx::from_string<std::chrono::year_month_day>(text)),
  74. pqxx::conversion_error,
  75. pqxx::internal::concat("Invalid date '", text, "' parsed as if valid."));
  76. }
  77. PQXX_REGISTER_TEST(test_date_string_conversion);
  78. #endif // PQXX_HAVE_YEAR_MONTH_DAY
  79. } // namespace