ORM C++
Loading...
Searching...
No Matches
projection.cppm
Go to the documentation of this file.
1module;
2
3#include <algorithm>
4#include <cstddef>
5#include <optional>
6#include <stdexcept>
7#include <string>
8#include <string_view>
9#include <type_traits>
10#include <utility>
11#include <vector>
12
13export module orm:dynamic_projection;
14
15import orm.reflection;
16import :foundation;
17import :model;
18import :expressions;
19import :dynamic_select;
20
21// projection_query.hpp
22namespace orm
23{
24
25namespace detail
26{
27inline auto isSupportedProjectionResultType(model::ColumnType type) -> bool
28{
29 switch (type)
30 {
48 return true;
49 }
50
51 return false;
52}
53
54struct ProjectionResultField
55{
56 std::string name;
57 std::optional<model::ColumnType> type;
58 model::TypeId cppType{};
59 bool uuidAdapted = false;
60};
61
62template <typename T>
63consteval auto projectionLogicalType() -> std::optional<model::ColumnType>
64{
65 using field_t = std::remove_cvref_t<T>;
66 using value_t = std::remove_cv_t<model::detail::static_optional_value_t<field_t>>;
67 if constexpr (requires { model::LogicalTypeTraits<value_t>::value; })
68 {
70 }
71 else
72 {
73 return std::nullopt;
74 }
75}
76
77template <typename Projection>
78auto projectionAlias(const Projection& projection) -> std::string_view
79{
80 if constexpr (requires { projection.resultField; })
81 return projection.resultField;
82 else
83 return projection.alias;
84}
85
86template <typename Projections>
87inline auto validateProjectionAliasNames(const Projections& projections,
88 const std::vector<ProjectionResultField>& fields) -> void
89{
90 if (projections.empty())
91 {
92 throw std::invalid_argument{"Projection query requires at least one projected field"};
93 }
94
95 std::vector<std::string> resultFields;
96 resultFields.reserve(fields.size());
97
98 for (const auto& field : fields)
99 {
100 if (not field.type.has_value() or not isSupportedProjectionResultType(field.type.value()))
101 {
102 throw std::invalid_argument{"Unsupported projection result field type: " + field.name};
103 }
104
105 resultFields.push_back(field.name);
106 }
107
108 std::vector<std::string> projectedFields;
109 projectedFields.reserve(projections.size());
110
111 for (const auto& projection : projections)
112 {
113 const std::string alias{projectionAlias(projection)};
114 if (alias.empty())
115 {
116 throw std::invalid_argument{"Projection alias must not be empty"};
117 }
118
119 if (std::find(resultFields.begin(), resultFields.end(), alias) == resultFields.end())
120 {
121 throw std::invalid_argument{"Projection alias does not match a result field: " + alias};
122 }
123
124 if constexpr (requires {
125 projection.sourceType;
126 projection.sourceUuidAdapted;
127 })
128 {
129 const auto field = std::ranges::find(fields, alias, &ProjectionResultField::name);
130 if (projection.sourceType && (projection.sourceUuidAdapted || field->uuidAdapted) &&
131 *projection.sourceType != field->cppType)
132 throw std::invalid_argument{"Projection UUID domain type does not match the result field"};
133 }
134
135 if (std::find(projectedFields.begin(), projectedFields.end(), alias) != projectedFields.end())
136 {
137 throw std::invalid_argument{"Duplicate projection alias: " + alias};
138 }
139
140 projectedFields.push_back(alias);
141 }
142
143 for (const auto& resultField : resultFields)
144 {
145 if (std::find(projectedFields.begin(), projectedFields.end(), resultField) == projectedFields.end())
146 {
147 throw std::invalid_argument{"Missing projection alias for result field: " + resultField};
148 }
149 }
150}
151
152template <typename Result, typename Projections>
153auto validateProjectionAliases(const Projections& projections) -> void
154{
155 std::vector<ProjectionResultField> resultFields;
156 resultFields.reserve(reflection::fieldCount<Result>);
157
158 [&]<std::size_t... Indices>(std::index_sequence<Indices...>)
159 {
160 constexpr auto fields = reflection::fields<Result>();
161 auto appendField = [&]<std::size_t Index>()
162 {
164 using value_t = query::detail::scalar_t<field_t>;
165 constexpr auto type = projectionLogicalType<field_t>();
166 resultFields.emplace_back(std::string{fields[Index].name}, type, model::typeId<value_t>(),
167 UuidDomainValue<value_t>);
168 };
169 (appendField.template operator()<Indices>(), ...);
170 }(std::make_index_sequence<reflection::fieldCount<Result>>{});
171
172 validateProjectionAliasNames(projections, resultFields);
173}
174}
175export
176{
177 // namespace detail
178
179 /**
180 * @brief A select query that returns a user-defined DTO instead of the full source model.
181 *
182 * @tparam Source The mapped ORM model used in FROM, WHERE, ORDER BY, and projected columns.
183 * @tparam Result The flat DTO hydrated from projected aliases.
184 */
185 template <typename Source, typename Result>
186 class ProjectionQuery
187 {
188 public:
189 ProjectionQuery() = default;
190
191 template <typename... Projections>
192// requires query::detail::ORM_QUERY_MODEL_PROJECTIONS<Source, Projections...> &&
193// query::detail::ORM_QUERY_UUID_PROJECTION_DOMAINS<Result, Projections...>
194 auto project(Projections... projections) -> ProjectionQuery<Source, Result>&
195 {
196 data.projections = {query::detail::erase(projections)...};
197 detail::validateProjectionAliases<Result>(data.projections);
198
199 return *this;
200 }
201
202 template <typename P>
203// requires query::detail::PredicateFor<P, Source>
204 auto where(const P& predicate) -> ProjectionQuery<Source, Result>&
205 {
206 data.predicate = query::detail::erase(predicate);
207
208 return *this;
209 }
210
211 template <typename P>
212// requires query::detail::PredicateFor<P, Source>
213 auto andWhere(const P& predicate) -> ProjectionQuery<Source, Result>&
214 {
215 data.predicate = data.predicate.has_value() ? data.predicate.value() && query::detail::erase(predicate) :
216 query::detail::erase(predicate);
217
218 return *this;
219 }
220
221 template <typename P>
222// requires query::detail::PredicateFor<P, Source>
223 auto orWhere(const P& predicate) -> ProjectionQuery<Source, Result>&
224 {
225 data.predicate = data.predicate.has_value() ? data.predicate.value() || query::detail::erase(predicate) :
226 query::detail::erase(predicate);
227
228 return *this;
229 }
230
231 template <typename... Orders>
232// requires query::detail::ORM_QUERY_MODEL_ORDERS<Source, Orders...>
233 auto orderBy(Orders... orders) -> ProjectionQuery<Source, Result>&
234 {
235 data.orderBy = {query::detail::erase(orders)...};
236
237 return *this;
238 }
239
240 template <typename... Columns>
241// requires query::detail::ORM_QUERY_MODEL_COLUMNS<Source, Columns...>
242 auto groupBy(Columns... columns) -> ProjectionQuery<Source, Result>&
243 {
244 data.groupBy = {query::detail::erase(columns)...};
245
246 return *this;
247 }
248
249 template <typename P>
250// requires query::detail::AggregatePredicateFor<P, Source>
251 auto having(const P& predicate) -> ProjectionQuery<Source, Result>&
252 {
253 data.having = query::detail::erase(predicate);
254
255 return *this;
256 }
257
258 template <typename P>
259// requires query::detail::AggregatePredicateFor<P, Source>
260 auto andHaving(const P& predicate) -> ProjectionQuery<Source, Result>&
261 {
262 data.having = data.having.has_value() ? data.having.value() && query::detail::erase(predicate) :
263 query::detail::erase(predicate);
264
265 return *this;
266 }
267
268 template <typename P>
269// requires query::detail::AggregatePredicateFor<P, Source>
270 auto orHaving(const P& predicate) -> ProjectionQuery<Source, Result>&
271 {
272 data.having = data.having.has_value() ? data.having.value() || query::detail::erase(predicate) :
273 query::detail::erase(predicate);
274
275 return *this;
276 }
279 {
280 data.isDistinct = true;
281
282 return *this;
283 }
285 inline auto offset(std::size_t offset) -> ProjectionQuery<Source, Result>&
286 {
287 data.offset = offset;
288
289 return *this;
290 }
292 inline auto limit(std::size_t limit) -> ProjectionQuery<Source, Result>&
293 {
294 data.limit = limit;
295
296 return *this;
297 }
300 {
301 data.shouldJoin = false;
302
303 return *this;
304 }
305
306 private:
307 template <typename>
308 friend class orm::OrmContext;
309 friend class orm::detail::QueryTestAccess;
310
311 [[nodiscard]] inline auto getData() const -> const query::detail::SelectSpec&
312 {
313 detail::validateProjectionAliases<Result>(data.projections);
314
315 return data;
316 }
317
318 query::detail::SelectSpec data;
319 };
320}
321} // namespace orm
auto distinct() -> ProjectionQuery< Source, Result > &
auto limit(std::size_t limit) -> ProjectionQuery< Source, Result > &
auto having(const P &predicate) -> ProjectionQuery< Source, Result > &
ProjectionQuery()=default
auto groupBy(Columns... columns) -> ProjectionQuery< Source, Result > &
auto andHaving(const P &predicate) -> ProjectionQuery< Source, Result > &
auto orderBy(Orders... orders) -> ProjectionQuery< Source, Result > &
auto offset(std::size_t offset) -> ProjectionQuery< Source, Result > &
auto orWhere(const P &predicate) -> ProjectionQuery< Source, Result > &
auto orHaving(const P &predicate) -> ProjectionQuery< Source, Result > &
auto disableJoining() -> ProjectionQuery< Source, Result > &
auto where(const P &predicate) -> ProjectionQuery< Source, Result > &
auto andWhere(const P &predicate) -> ProjectionQuery< Source, Result > &
auto project(Projections... projections) -> ProjectionQuery< Source, Result > &
consteval auto logicalType() -> ColumnType
Resolves a C++ field type to its logical database type at compile time. Users may extend the closed s...
Definition mapping.cppm:528
consteval auto typeId() noexcept -> TypeId
Definition views.cppm:35
std::remove_reference_t< std::tuple_element_t< Index, typename detail::ReflectionTraits< detail::ReflectedType< T > >::Tuple > > field_type_t
consteval auto fields() noexcept
constexpr std::size_t fieldCount