Search code examples
c++postgresqllibpqxx

How to correctly select date field using libpqxx?


I am trying to select date field from PostgreSQL database using libpqxx and C++.

I would use this code, but I don't know if it is legal. I have searched in the documentation but I haven't any documented way.

using time_point = std::chrono::steady_clock::time_point;

pqxx::work txn(c);
auto&& rst = txn.exec("SELECT date FROM table");

for(auto&& row : rst)
  time_point date = row[0].as<time_point>();

Is this okey please? Do you know any better alternative?

I would like the same with date time and time field. Is there any difference please?

Thank you.

--

the documentation for field type: https://libpqxx.readthedocs.io/en/6.4/a01063.html#a3a55f6b44040b68e70382d9db7dea457


Solution

  • The answer on Github by JadeMatrix:

    field.as<>() will work with any type for which a specialization of pqxx::string_traits<> exists. libpqxx comes with support for std::string, builtin numerics (int, etc.), and maybe a few others I don't remember. Support for std::chrono:: types are missing by default, unfortunately. You can implement your own, but be warned that they will only work for TIMESTAMP WITHOUT TIME ZONE, DATE, TIME WITHOUT TIME ZONE, and INTERVAL. To correctly support … WITH TIME ZONE you will need Howard Hinnant's date library, which is what I use (there is talk of adding it to the standard library). If you want, I can share my code, which relies on date functionality for parsing Postgres date/time strings (ISO 8601 format).