ORM C++
Loading...
Searching...
No Matches
projection.cppm
Go to the documentation of this file.
1module;
2
3#include <concepts>
4#include <cstddef>
5#include <optional>
6#include <string>
7#include <tuple>
8#include <type_traits>
9#include <utility>
10#include <variant>
11#include <vector>
12
13export module orm:query_projection;
14
15import orm.reflection;
16import :foundation;
17import :model_mapping;
18import :model_columns;
19import :model_views;
20import :query_value;
21import :query_runtime_predicate;
22import :query_parameters;
23import :query_expression;
24import :query_columns;
25import :query_aggregate;
26
27// query/OrderBy.hpp
28namespace orm::query::detail
29{
30enum class OrderDirection
31{
32 Asc,
33 Desc,
34};
35
36/**
37 * @brief A single ORDER BY clause.
38 */
39struct OrderBy
40{
41 Column column{""};
42 OrderDirection direction{OrderDirection::Asc};
43 std::string rawSql{};
44 bool isRaw{false};
45};
46
47/**
48 * @brief Creates an ascending ORDER BY clause.
49 */
50inline auto asc(Column column) -> OrderBy
51{
52 return OrderBy{.column = std::move(column), .direction = OrderDirection::Asc};
53}
54
55/**
56 * @brief Creates a descending ORDER BY clause.
57 */
58inline auto desc(Column column) -> OrderBy
59{
60 return OrderBy{.column = std::move(column), .direction = OrderDirection::Desc};
61}
62
63/**
64 * @brief Creates a raw ORDER BY clause.
65 */
66inline auto rawOrder(std::string sql) -> OrderBy
67{
68 return OrderBy{.rawSql = std::move(sql), .isRaw = true};
69}
70} // namespace orm::query::detail
71
72namespace orm::query
73{
74export
75{
76
77 template <typename Owner>
78 class TypedOrderBy
79 {
80 public:
81 using Model = Owner;
82 using ParameterTypes = std::tuple<>;
83 inline static constexpr auto kind = ExprKind::DynamicOrder;
84 inline static constexpr bool isOrder = true;
85 inline static constexpr bool staticSqlEligible = false;
86 template <typename E>
87// requires detail::isExpression<E> && E::isOrder && detail::ORM_QUERY_MODEL<E, Owner> &&
88// detail::ORM_QUERY_UNBOUND_PARAMETER<E>
89 TypedOrderBy(const E& expression) : data{detail::erase(expression)}
90 {
91 }
92 template <typename E>
93// requires detail::isExpression<E> && E::isOrder && detail::ORM_QUERY_MODEL<E, Owner> &&
94// detail::ORM_QUERY_UNBOUND_PARAMETER<E>
95 auto operator=(const E& expression) -> TypedOrderBy&
96 {
97 data = detail::erase(expression);
98 return *this;
99 }
100 auto dynamic() const -> TypedOrderBy
101 {
102 return *this;
103 }
104
105 private:
106 friend struct detail::TypedAccess;
107 explicit TypedOrderBy(detail::OrderBy value) : data{std::move(value)} {}
108 auto runtime() const -> detail::OrderBy
109 {
110 return data;
111 }
112 detail::OrderBy data;
113 };
114}
115} // namespace orm::query
116
117namespace orm::query::detail
118{
119template <typename C, OrderDirection Direction>
120struct OrderMeta : ExpressionMeta<typename C::Model>
121{
122 using Source = C;
123 using Dynamic = TypedOrderBy<typename C::Model>;
124 inline static constexpr auto direction = Direction;
125 inline static constexpr bool isOrder = true;
126 inline static constexpr bool staticSqlEligible = true;
127 template <typename Children, typename Args>
128 static auto render(const Children& children, const Args& args)
129 {
130 return OrderBy{.column = TypedAccess::erase(std::get<0>(children), args), .direction = Direction};
131 }
132 template <typename Children, typename Args, typename Callback>
133 static auto visit(const Children&, const Args&, Callback&) -> void
134 {
135 }
136};
137template <typename E>
138struct IsTypedOrderBy : std::false_type
139{
140};
141template <typename M>
142struct IsTypedOrderBy<TypedOrderBy<M>> : std::true_type
143{
144};
145template <typename E, typename M>
146concept OrderFor =
147 (IsTypedOrderBy<std::remove_cvref_t<E>>::value || isExpression<E>) && std::remove_cvref_t<E>::isOrder &&
148 ORM_QUERY_MODEL<std::remove_cvref_t<E>, M> && ORM_QUERY_UNBOUND_PARAMETER<E>;
149template <typename M, typename... Orders>
150concept ORM_QUERY_MODEL_ORDERS = (OrderFor<Orders, M> && ...);
151} // namespace orm::query::detail
152
153namespace orm::query
154{
155export
156{
157
158 template <auto... Members>
159// requires detail::ORM_QUERY_ORDERABLE<typename TypedColumn<Members...>::Value>
160 constexpr auto asc(TypedColumn<Members...> column)
161 {
162 return detail::makeExpression<ExprKind::Order,
163 detail::OrderMeta<TypedColumn<Members...>, detail::OrderDirection::Asc>>(column);
164 }
165 template <auto... Members>
166// requires detail::ORM_QUERY_ORDERABLE<typename TypedColumn<Members...>::Value>
167 constexpr auto desc(TypedColumn<Members...> column)
168 {
169 return detail::makeExpression<ExprKind::Order,
170 detail::OrderMeta<TypedColumn<Members...>, detail::OrderDirection::Desc>>(column);
171 }
172 template <typename M>
173 auto rawOrder(std::string sql) -> TypedOrderBy<M>
174 {
175 return detail::TypedAccess::make<TypedOrderBy<M>>(detail::rawOrder(std::move(sql)));
176 }
177}
178} // namespace orm::query
179
180// query/Projection.hpp
181namespace orm::query::detail
182{
183using ProjectionSource = std::variant<Column, AggregateExpression>;
184
185/**
186 * @brief A projected source expression and the DTO field alias it hydrates.
187 */
188struct Projection
189{
190 std::string resultField;
191 ProjectionSource source;
192 std::optional<model::TypeId> sourceType{};
193 bool sourceUuidAdapted = false;
194};
195
196/**
197 * @brief Projects a source model column path into a result DTO field.
198 */
199inline auto as(std::string resultField, Column sourceColumn) -> Projection
200{
201 return Projection{.resultField = std::move(resultField), .source = std::move(sourceColumn)};
202}
203
204/**
205 * @brief Projects an aggregate expression into a result DTO field.
206 */
207inline auto as(std::string resultField, AggregateExpression aggregate) -> Projection
208{
209 return Projection{.resultField = std::move(resultField), .source = std::move(aggregate)};
210}
211
212} // namespace orm::query::detail
213
214namespace orm::query
215{
216export
217{
218
219 template <typename Owner>
220 class TypedProjection
221 {
222 public:
223 using Model = Owner;
224 using ParameterTypes = std::tuple<>;
225 inline static constexpr auto kind = ExprKind::DynamicProjection;
226 inline static constexpr bool isProjection = true;
227 inline static constexpr bool staticSqlEligible = false;
228 template <typename E>
229// requires detail::isExpression<E> && E::isProjection && detail::ORM_QUERY_MODEL<E, Owner> &&
230// detail::ORM_QUERY_UNBOUND_PARAMETER<E>
231 TypedProjection(const E& expression) : data{detail::erase(expression)}
232 {
233 }
234 template <typename E>
235// requires detail::isExpression<E> && E::isProjection && detail::ORM_QUERY_MODEL<E, Owner> &&
236// detail::ORM_QUERY_UNBOUND_PARAMETER<E>
237 auto operator=(const E& expression) -> TypedProjection&
238 {
239 data = detail::erase(expression);
240 return *this;
242 auto dynamic() const -> TypedProjection
243 {
244 return *this;
245 }
246
247 private:
248 friend struct detail::TypedAccess;
249 explicit TypedProjection(detail::Projection value) : data{std::move(value)} {}
250 auto runtime() const -> detail::Projection
251 {
252 return data;
253 }
254 detail::Projection data;
255 };
256}
257} // namespace orm::query
258
259namespace orm::query::detail
260{
261template <typename S, reflection::FixedString Alias>
262struct ProjectionMeta : ExpressionMeta<typename S::Model>
263{
264 using Source = S;
265 using Dynamic = TypedProjection<typename S::Model>;
266 inline static constexpr auto alias = Alias;
267 inline static constexpr bool isProjection = true;
268 inline static constexpr bool staticSqlEligible = detail::staticSqlEligible<S>;
269 template <typename Children, typename Args>
270 static auto render(const Children& children, const Args& args)
271 {
272 auto projection = detail::as(std::string{Alias.view()}, TypedAccess::erase(std::get<0>(children), args));
273 projection.sourceType = model::typeId<typename S::Value>();
274 projection.sourceUuidAdapted = UuidDomainValue<typename S::Value>;
275 return projection;
276 }
277 template <typename Children, typename Args, typename Callback>
278 static auto visit(const Children&, const Args&, Callback&) -> void
279 {
280 }
281};
282template <typename S>
283struct RuntimeProjectionMeta : ExpressionMeta<typename S::Model>
284{
285 using Source = S;
286 using Dynamic = TypedProjection<typename S::Model>;
287 inline static constexpr bool isProjection = true;
288 inline static constexpr bool staticSqlEligible = false;
289 template <typename Children, typename Args>
290 static auto render(const Children& children, const Args& args)
291 {
292 auto projection = detail::as(std::get<1>(children), TypedAccess::erase(std::get<0>(children), args));
293 projection.sourceType = model::typeId<typename S::Value>();
294 projection.sourceUuidAdapted = UuidDomainValue<typename S::Value>;
295 return projection;
296 }
297 template <typename Children, typename Args, typename Callback>
298 static auto visit(const Children&, const Args&, Callback&) -> void
299 {
300 }
301};
302template <typename E>
303struct IsTypedProjection : std::false_type
304{
305};
306template <typename M>
307struct IsTypedProjection<TypedProjection<M>> : std::true_type
308{
309};
310template <typename E, typename M>
311concept ProjectionFor =
312 (IsTypedProjection<std::remove_cvref_t<E>>::value || isExpression<E>) && std::remove_cvref_t<E>::isProjection &&
313 ORM_QUERY_MODEL<std::remove_cvref_t<E>, M> && ORM_QUERY_UNBOUND_PARAMETER<E>;
314template <typename M, typename... Projections>
315concept ORM_QUERY_MODEL_PROJECTIONS = (ProjectionFor<Projections, M> && ...);
316
317// A statically named projection retains the source C++ type. Preserve that
318// type when either side uses an application UUID adapter, rather than
319// silently converting one domain identifier into another through orm::Uuid.
320template <typename Result, typename Projection>
321consteval auto uuidProjectionDomainCompatible() -> bool
322{
323 using P = std::remove_cvref_t<Projection>;
324 if constexpr (requires {
325 P::alias;
326 typename P::Source;
327 })
328 {
329 using source_t = typename P::Source::Value;
330 constexpr auto fields = reflection::fields<Result>();
331 bool compatible = true;
332 [&]<std::size_t... I>(std::index_sequence<I...>) consteval
333 {
334 auto check = [&]<std::size_t Index>() consteval
335 {
336 using target_t = scalar_t<reflection::field_type_t<Result, Index>>;
337 if constexpr (UuidDomainValue<source_t> || UuidDomainValue<target_t>)
338 if (fields[Index].name == P::alias.view())
339 compatible = std::same_as<source_t, target_t>;
340 };
341 (check.template operator()<I>(), ...);
342 }(std::make_index_sequence<reflection::fieldCount<Result>>{});
343 return compatible;
344 }
345 else
346 return true;
347}
348template <typename Result, typename... Projections>
349concept ORM_QUERY_UUID_PROJECTION_DOMAINS = (uuidProjectionDomainCompatible<Result, Projections>() && ...);
350
351template <typename S>
352concept ProjectionSourceExpression = IsTypedColumn<std::remove_cvref_t<S>>::value || AggregateExpressionType<S>;
353} // namespace orm::query::detail
354
355namespace orm::query
356{
357export
358{
359
360 template <typename S>
361// requires detail::ProjectionSourceExpression<S>
362 constexpr auto as(std::string alias, S source)
363 {
364 return detail::makeExpression<ExprKind::Projection, detail::RuntimeProjectionMeta<S>>(source, std::move(alias));
365 }
366 template <reflection::FixedString Alias, typename S>
367// requires detail::ProjectionSourceExpression<S>
368 constexpr auto as(S source)
369 {
370 return detail::makeExpression<ExprKind::Projection, detail::ProjectionMeta<S, Alias>>(source);
371 }
372}
373} // namespace orm::query
374
375// query/SelectSpec.hpp
376namespace orm::query::detail
377{
378/**
379 * @brief Runtime SELECT options independent from static model metadata.
380 */
381struct SelectSpec
382{
383 std::optional<std::size_t> offset = std::nullopt;
384 std::optional<std::size_t> limit = std::nullopt;
385 std::optional<Predicate> predicate = std::nullopt;
386 std::vector<OrderBy> orderBy;
387 std::vector<Projection> projections;
388 std::vector<Column> groupBy;
389 std::optional<AggregatePredicate> having = std::nullopt;
390 std::vector<std::string> includes;
391 bool isDistinct = false;
392 bool shouldJoin = true;
393};
394} // namespace orm::query::detail
395
396// query/UpdateSpec.hpp
397namespace orm::query::detail
398{
399struct UpdateValue
400{
401 std::optional<QueryValue> value;
402};
403
404struct UpdateAssignment
405{
406 Column column;
407 UpdateValue value;
408};
409
410/**
411 * @brief Runtime UPDATE options independent from static model metadata.
412 */
413struct UpdateSpec
414{
415 std::vector<UpdateAssignment> assignments;
416 std::optional<Predicate> predicate = std::nullopt;
417};
418} // namespace orm::query::detail
auto dynamic() const -> TypedOrderBy
auto operator=(const E &expression) -> TypedOrderBy &
TypedOrderBy(const E &expression)
TypedProjection(const E &expression)
auto operator=(const E &expression) -> TypedProjection &
auto dynamic() const -> TypedProjection
orm::query::detail::Column Column
orm::query::detail::UpdateValue UpdateValue
orm::query::detail::OrderBy OrderBy
consteval auto typeId() noexcept -> TypeId
Definition views.cppm:35
constexpr auto asc(TypedColumn< Members... > column)
constexpr auto desc(TypedColumn< Members... > column)
constexpr auto as(std::string alias, S source)
auto rawOrder(std::string sql) -> TypedOrderBy< M >
consteval auto fields() noexcept