From a032632f68905543d21d1c279176e001f38d6fcb Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sun, 8 Nov 2015 15:53:35 +0000 Subject: Support extracting nullable fields into boost::optionals --- libdbpp/column.h | 11 +++++++++++ libdbpp/unittests/testUtils.cpp | 16 ++++++++++++++++ libdbpp/unittests/util.sql | 1 + 3 files changed, 28 insertions(+) diff --git a/libdbpp/column.h b/libdbpp/column.h index 37f3b88..43d2687 100644 --- a/libdbpp/column.h +++ b/libdbpp/column.h @@ -4,6 +4,7 @@ #include #include #include +#include #include namespace DB { @@ -53,6 +54,16 @@ namespace DB { void operator>>(boost::posix_time::time_duration &) const; /// STL like date time extractor. void operator>>(boost::posix_time::ptime &) const; + template + void operator>>(boost::optional & v) const { + if (!isNull()) { + v = T(); + operator>>(v.get()); + } + else { + v = boost::none; + } + } /// This column's ordinal. const unsigned int colNo; diff --git a/libdbpp/unittests/testUtils.cpp b/libdbpp/unittests/testUtils.cpp index e43faae..b7947c7 100644 --- a/libdbpp/unittests/testUtils.cpp +++ b/libdbpp/unittests/testUtils.cpp @@ -33,6 +33,22 @@ BOOST_AUTO_TEST_CASE( forEachRow ) }); } +BOOST_AUTO_TEST_CASE( forEachRowNulls ) +{ + auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); + auto sel = DB::SelectCommandPtr(db->newSelectCommand("SELECT a, b, c, d, e, f FROM forEachRow ORDER BY a DESC LIMIT 1")); + sel->forEachRow, std::string, boost::optional, boost::optional, bool>( + [](auto a, auto b, auto c, auto d, auto e, auto f) { + BOOST_REQUIRE_EQUAL(2, a); + BOOST_REQUIRE(b); + BOOST_REQUIRE_EQUAL(2.3, *b); + BOOST_REQUIRE_EQUAL("Some text", c); + BOOST_REQUIRE(!d); + BOOST_REQUIRE(!e); + BOOST_REQUIRE_EQUAL(false, f); + }); +} + BOOST_AUTO_TEST_CASE( execute ) { auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); diff --git a/libdbpp/unittests/util.sql b/libdbpp/unittests/util.sql index fe98fc9..04c6bf6 100644 --- a/libdbpp/unittests/util.sql +++ b/libdbpp/unittests/util.sql @@ -6,4 +6,5 @@ CREATE TABLE foreachrow ( e interval, f boolean); INSERT INTO foreachrow(a, b, c, d, e, f) VALUES(1, 2.3, 'Some text', '2015-11-07 13:39:17', '04:03:02', true); +INSERT INTO foreachrow(a, b, c, f) VALUES(2, 2.3, 'Some text', false); -- cgit v1.2.3