From a749f5aabd08c7e21bb3b6b5a6caece144105dc1 Mon Sep 17 00:00:00 2001 From: "Dr. Patrick Urbanke" Date: Tue, 15 Apr 2025 08:40:10 +0200 Subject: [PATCH] Designed read as a functor --- include/sqlgen/read.hpp | 22 ++++++++-- tests/sqlite/test_write_and_read_to_file.cpp | 44 ++++++++++++++++++++ 2 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 tests/sqlite/test_write_and_read_to_file.cpp diff --git a/include/sqlgen/read.hpp b/include/sqlgen/read.hpp index aa3380a..5ab068b 100644 --- a/include/sqlgen/read.hpp +++ b/include/sqlgen/read.hpp @@ -11,7 +11,7 @@ namespace sqlgen { template -Result read(const Ref& _conn) noexcept { +Result read_impl(const Ref& _conn) { if constexpr (internal::is_range_v) { using ValueType = typename ContainerType::value_type::value_type; const auto query = transpilation::to_select_from(); @@ -32,16 +32,30 @@ Result read(const Ref& _conn) noexcept { }; using ValueType = typename ContainerType::value_type; - return read>(_conn).and_then(to_container); + return read_impl>(_conn).and_then(to_container); } } template -Result read(const Result>& _res) noexcept { +Result read_impl(const Result>& _res) { return _res.and_then( - [](const auto& _conn) { return read(_conn); }); + [](const auto& _conn) { return read_impl(_conn); }); } +template +struct Read { + Result operator()(const auto& _conn) const noexcept { + try { + return read_impl(_conn); + } catch (std::exception& e) { + return error(e.what()); + } + } +}; + +template +const auto read = Read(); + } // namespace sqlgen #endif diff --git a/tests/sqlite/test_write_and_read_to_file.cpp b/tests/sqlite/test_write_and_read_to_file.cpp new file mode 100644 index 0000000..4633617 --- /dev/null +++ b/tests/sqlite/test_write_and_read_to_file.cpp @@ -0,0 +1,44 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_write_and_read_to_file { + +struct Person { + sqlgen::PrimaryKey id; + std::string first_name; + std::string last_name; + int age; +}; + +TEST(sqlite, test_write_and_read_to_file) { + const auto people1 = std::vector( + {Person{ + .id = 0, .first_name = "Homer", .last_name = "Simpson", .age = 45}, + Person{.id = 1, .first_name = "Bart", .last_name = "Simpson", .age = 10}, + Person{.id = 2, .first_name = "Lisa", .last_name = "Simpson", .age = 8}, + Person{ + .id = 3, .first_name = "Maggie", .last_name = "Simpson", .age = 0}}); + + sqlgen::sqlite::connect("test.db") + .and_then([&](auto&& _conn) { return sqlgen::write(_conn, people1); }) + .value(); + + const auto people2 = sqlgen::sqlite::connect("test.db") + .and_then(sqlgen::read>) + .value(); + + std::remove("test.db"); + + const auto json1 = rfl::json::write(people1); + const auto json2 = rfl::json::write(people2); + + EXPECT_EQ(json1, json2); +} + +} // namespace test_write_and_read_to_file