query/include/matador/query/query_collection_resolver.hpp

90 lines
3.0 KiB
C++

#ifndef MATADOR_QUERY_CONTAINER_RESOLVER_HPP
#define MATADOR_QUERY_CONTAINER_RESOLVER_HPP
#include "matador/object/collection_resolver.hpp"
#include "matador/object/object_resolver.hpp"
#include "matador/sql/internal/identifier_statement_binder.hpp"
#include "matador/sql/statement.hpp"
namespace matador::sql {
class executor;
}
namespace matador::query {
template<typename Type>
class query_collection_resolver : public object::collection_resolver<Type> {
public:
explicit query_collection_resolver(sql::statement &&stmt,
const std::type_index& root_type,
std::string join_column,
const std::shared_ptr<object::object_resolver<typename Type::value_type>> &resolver)
: object::collection_resolver<Type>(root_type, join_column)
, stmt_(std::move(stmt))
, resolver_(resolver)
{}
std::vector<Type> resolve(const utils::identifier &id) override;
protected:
sql::statement stmt_;
std::type_index index{typeid(Type)};
std::shared_ptr<object::object_resolver<typename Type::value_type>> resolver_;
};
struct value_to_identifier{
void operator()(const int8_t &x) { assign(x); }
void operator()(const int16_t &x) { assign(x); }
void operator()(const int32_t &x) { assign(x); }
void operator()(const int64_t &x) { assign(x); }
void operator()(const uint8_t &x) { assign(x); }
void operator()(const uint16_t &x) { assign(x); }
void operator()(const uint32_t &x) { assign(x); }
void operator()(const uint64_t &x) { assign(x); }
void operator()(const bool &) {}
void operator()(const float &) {}
void operator()(const double &) {}
void operator()(const char *) {}
void operator()(const std::string &x) { assign(x); }
void operator()(const utils::date_type_t &) {}
void operator()(const utils::time_type_t &) {}
void operator()(const utils::timestamp_type_t &) {}
void operator()(const utils::blob_type_t &) {}
template<typename Type>
void assign(const Type &x) { id_ = x; }
utils::identifier id_;
};
struct identifier_creator {
value_to_identifier visitor;
void on_attribute(const char*, const utils::value &val, const utils::field_attributes &/*attr*/) {
std::visit(visitor, val.raw_value());
}
};
template<typename Type>
std::vector<Type> query_collection_resolver<Type>::resolve(const utils::identifier &id) {
sql::identifier_statement_binder binder(stmt_);
binder.bind(id);
auto result = stmt_.fetch();
if (!result) {
return {};
}
std::vector<Type> out;
for (auto &r : *result) {
// Todo: convert the first value of record into an utils::identifier
// then create a object_proxy<Type>(resolver, identifier)
if (r.size() != 1) {
continue;
}
identifier_creator creator;
r.at(0).process(creator);
const auto op = std::make_shared<object::object_proxy<typename Type::value_type>>(resolver_, creator.visitor.id_);
out.emplace_back(op);
}
return out;
}
}
#endif //MATADOR_QUERY_CONTAINER_RESOLVER_HPP