Designed read as a functor

This commit is contained in:
Dr. Patrick Urbanke
2025-04-15 08:40:10 +02:00
parent 1306aec37a
commit a749f5aabd
2 changed files with 62 additions and 4 deletions

View File

@@ -11,7 +11,7 @@
namespace sqlgen {
template <class ContainerType>
Result<ContainerType> read(const Ref<Connection>& _conn) noexcept {
Result<ContainerType> read_impl(const Ref<Connection>& _conn) {
if constexpr (internal::is_range_v<ContainerType>) {
using ValueType = typename ContainerType::value_type::value_type;
const auto query = transpilation::to_select_from<ValueType>();
@@ -32,16 +32,30 @@ Result<ContainerType> read(const Ref<Connection>& _conn) noexcept {
};
using ValueType = typename ContainerType::value_type;
return read<Range<ValueType>>(_conn).and_then(to_container);
return read_impl<Range<ValueType>>(_conn).and_then(to_container);
}
}
template <class ContainerType>
Result<ContainerType> read(const Result<Ref<Connection>>& _res) noexcept {
Result<ContainerType> read_impl(const Result<Ref<Connection>>& _res) {
return _res.and_then(
[](const auto& _conn) { return read<ContainerType>(_conn); });
[](const auto& _conn) { return read_impl<ContainerType>(_conn); });
}
template <class ContainerType>
struct Read {
Result<ContainerType> operator()(const auto& _conn) const noexcept {
try {
return read_impl<ContainerType>(_conn);
} catch (std::exception& e) {
return error(e.what());
}
}
};
template <class ContainerType>
const auto read = Read<ContainerType>();
} // namespace sqlgen
#endif

View File

@@ -0,0 +1,44 @@
#include <gtest/gtest.h>
#include <cstdio>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <sqlgen.hpp>
#include <sqlgen/sqlite.hpp>
#include <vector>
namespace test_write_and_read_to_file {
struct Person {
sqlgen::PrimaryKey<uint32_t> 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>(
{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<std::vector<Person>>)
.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