ORM C++
Loading...
Searching...
No Matches
static_plan.cppm
Go to the documentation of this file.
1module;
2
3#include <concepts>
4#include <cstddef>
5#include <limits>
6#include <optional>
7#include <stdexcept>
8#include <tuple>
9#include <type_traits>
10#include <utility>
11
12export module orm:static_plan;
13
14import orm.reflection;
15import :foundation;
16import :model;
17import :expressions;
18import :dynamic_query;
19
20// query/StaticPlan.hpp
21namespace orm::query::detail
22{
23enum class PlanOperation
24{
25 Select,
26 Update,
27 Remove
28};
29struct NoClause
30{
31};
32template <auto Member>
33struct IncludeTag
34{
35 inline static constexpr auto member = Member;
36};
37
38struct PlanAccess
39{
40 template <typename P, typename S>
41 static constexpr auto make(S&& state) -> P
42 {
43 return P{std::forward<S>(state)};
44 }
45 template <typename P>
46 static constexpr auto get(const P& plan) -> const typename P::State&
47 {
48 return plan.state;
49 }
50};
51
52template <typename Column, typename ValueStorage>
53struct Assignment
54{
55 using Source = Column;
56 using Stored = ValueStorage;
57 using ParameterTypes = detail::ParameterTypes<ValueStorage>;
58 ValueStorage value;
59};
60
61template <typename T>
62inline constexpr bool isStaticPlan = false;
63template <typename C, typename V>
64inline constexpr bool setCompatible = []
65{
66 using T = parameter_value_t<V>;
67 if constexpr (std::same_as<T, std::nullopt_t> || std::same_as<T, std::nullptr_t>)
68 return C::nullable;
69 else if constexpr (model::isNullable<T>)
70 return C::nullable && compatibleValue<typename C::Value, scalar_t<T>>;
71 else
72 return compatibleValue<typename C::Value, T>;
73}();
74template <typename C, typename V>
75concept ORM_QUERY_SET_VALUE = setCompatible<C, V>;
76
77template <typename C, typename V, typename Args>
78auto applyAssignment(orm::Update<typename C::Model>& result, const Assignment<C, V>& assignment,
79 const Args& args) -> void
80{
81 auto value = resolveValue(assignment.value, args);
82 if constexpr (std::same_as<decltype(value), std::nullptr_t>)
83 result.set(TypedAccess::make<C>(), std::nullopt);
84 else
85 result.set(TypedAccess::make<C>(), std::move(value));
86}
87} // namespace orm::query::detail
88
89namespace orm::query
90{
91export
92{
93
94 /** An immutable, reusable query shape. Values are owned and bound at execution. */
95 template <detail::PlanOperation Operation, typename Owner, typename ResultType, typename StateTuple,
96 bool Distinct = false, bool Join = true>
97 class StaticPlan
98 {
99 public:
100 using Model = Owner;
101 using Result = ResultType;
102 using State = StateTuple;
103 using ParameterTypes = detail::ParameterTypes<State>;
104 using Predicate = std::tuple_element_t<0, State>;
105 using Orders = std::tuple_element_t<1, State>;
106 using Groups = std::tuple_element_t<2, State>;
107 using Having = std::tuple_element_t<3, State>;
108 using Projections = std::tuple_element_t<4, State>;
109 using Assignments = std::tuple_element_t<5, State>;
110 using Limit = std::tuple_element_t<6, State>;
111 using Offset = std::tuple_element_t<7, State>;
112 using Includes = std::tuple_element_t<8, State>;
113 inline static constexpr auto operation = Operation;
114 inline static constexpr bool isDistinct = Distinct;
115 inline static constexpr bool shouldJoin = Join;
116 inline static constexpr bool isProjection = !std::same_as<Projections, std::tuple<>>;
117 inline static constexpr bool hasPredicate = !std::same_as<Predicate, detail::NoClause>;
118 inline static constexpr bool hasHaving = !std::same_as<Having, detail::NoClause>;
119 inline static constexpr bool hasLimit = !std::same_as<Limit, detail::NoClause>;
120 inline static constexpr bool hasOffset = !std::same_as<Offset, detail::NoClause>;
121
122 template <typename P>
123// requires detail::PlanPredicateFor<P, Model> &&
124// (Operation == detail::PlanOperation::Select || detail::ORM_QUERY_WRITE_SAFE<P>)
125 constexpr auto where(P predicate) const
126 {
127 return replace<0>(std::move(predicate));
128 }
129 template <typename P>
130// requires detail::PlanPredicateFor<P, Model> &&
131// (Operation == detail::PlanOperation::Select || detail::ORM_QUERY_WRITE_SAFE<P>)
132 constexpr auto andWhere(P predicate) const
133 {
134 if constexpr (hasPredicate)
135 return where(std::get<0>(state) && std::move(predicate));
136 else
137 return where(std::move(predicate));
138 }
139 template <typename P>
140// requires detail::PlanPredicateFor<P, Model> &&
141// (Operation == detail::PlanOperation::Select || detail::ORM_QUERY_WRITE_SAFE<P>)
142 constexpr auto orWhere(P predicate) const
143 {
144 if constexpr (hasPredicate)
145 return where(std::get<0>(state) || std::move(predicate));
146 else
147 return where(std::move(predicate));
148 }
149 template <typename... O>
150// requires(Operation == detail::PlanOperation::Select) && detail::ORM_QUERY_MODEL_ORDERS<Model, O...>
151 constexpr auto orderBy(O... orders) const
152 {
153 return replace<1>(std::tuple{std::move(orders)...});
154 }
155 template <typename... C>
156// requires(Operation == detail::PlanOperation::Select) && detail::ORM_QUERY_MODEL_COLUMNS<Model, C...>
157 constexpr auto groupBy(C... columns) const
158 {
159 return replace<2>(std::tuple{std::move(columns)...});
160 }
161 template <typename P>
162// requires(Operation == detail::PlanOperation::Select) && detail::PlanAggregatePredicateFor<P, Model>
163 constexpr auto having(P predicate) const
164 {
165 return replace<3>(std::move(predicate));
166 }
167 template <typename P>
168// requires(Operation == detail::PlanOperation::Select) && detail::PlanAggregatePredicateFor<P, Model>
169 constexpr auto andHaving(P predicate) const
170 {
171 if constexpr (hasHaving)
172 return having(std::get<3>(state) && std::move(predicate));
173 else
174 return having(std::move(predicate));
175 }
176 template <typename P>
177// requires(Operation == detail::PlanOperation::Select) && detail::PlanAggregatePredicateFor<P, Model>
178 constexpr auto orHaving(P predicate) const
179 {
180 if constexpr (hasHaving)
181 return having(std::get<3>(state) || std::move(predicate));
182 else
183 return having(std::move(predicate));
184 }
185 template <typename... P>
186// requires(Operation == detail::PlanOperation::Select) && isProjection &&
187// detail::ORM_QUERY_MODEL_PROJECTIONS<Model, P...> &&
188// detail::ORM_QUERY_UUID_PROJECTION_DOMAINS<Result, P...>
189 constexpr auto project(P... projections) const
190 {
191 static_assert(sizeof...(P) > 0, "ORM_QUERY_PROJECTION: a projection plan requires projected fields");
192 return replace<4>(std::tuple{std::move(projections)...});
194 constexpr auto distinct() const
195// requires(Operation == detail::PlanOperation::Select)
196 {
197 return detail::PlanAccess::make<StaticPlan<Operation, Model, Result, State, true, Join>>(state);
199 constexpr auto disableJoining() const
200// requires(Operation == detail::PlanOperation::Select)
201 {
202 return detail::PlanAccess::make<StaticPlan<Operation, Model, Result, State, Distinct, false>>(state);
204 constexpr auto limit(std::size_t value) const
205// requires(Operation == detail::PlanOperation::Select)
206 {
207 return replace<6>(value);
209 constexpr auto offset(std::size_t value) const
210// requires(Operation == detail::PlanOperation::Select)
211 {
212 return replace<7>(value);
213 }
214 template <std::size_t I>
215 constexpr auto limit(Parameter<std::size_t, I> value) const
216// requires(Operation == detail::PlanOperation::Select)
217 {
218 return replace<6>(value);
219 }
220 template <std::size_t I>
221 constexpr auto offset(Parameter<std::size_t, I> value) const
222// requires(Operation == detail::PlanOperation::Select)
223 {
224 return replace<7>(value);
225 }
226 template <auto Member>
227// requires(Operation == detail::PlanOperation::Select) &&
228// (!isProjection) && detail::ORM_QUERY_COLLECTION<Member> &&
229// detail::ORM_QUERY_MODEL_TYPE<typename detail::CollectionTraits<Member>::Model, Model>
230 constexpr auto include() const
231 {
232 constexpr bool alreadyIncluded = []<std::size_t... I>(std::index_sequence<I...>) consteval {
233 return (std::same_as<std::tuple_element_t<I, Includes>, detail::IncludeTag<Member>> || ...);
234 }(std::make_index_sequence<std::tuple_size_v<Includes>>{});
235 if constexpr (alreadyIncluded)
236 return *this;
237 else
238 return replace<8>(std::tuple_cat(std::get<8>(state), std::tuple{detail::IncludeTag<Member>{}}));
239 }
240 template <auto... Members, typename V>
241// requires(Operation == detail::PlanOperation::Update) && detail::ColumnFor<TypedColumn<Members...>, Model> &&
242// detail::ORM_QUERY_WRITE_SAFE<TypedColumn<Members...>> &&
243// detail::ORM_QUERY_SET_VALUE<TypedColumn<Members...>, V>
244 constexpr auto set(TypedColumn<Members...>, V&& value) const
245 {
246 auto stored = detail::captureValue(std::forward<V>(value));
247 using A = detail::Assignment<TypedColumn<Members...>, decltype(stored)>;
248 return replace<5>(std::tuple_cat(std::get<5>(state), std::tuple{A{std::move(stored)}}));
250 static consteval auto validateShape() -> void
251 {
252 if constexpr (Operation != detail::PlanOperation::Select)
253 static_assert(hasPredicate, "ORM_QUERY_REQUIRED_WHERE: a mutation plan requires WHERE");
254 if constexpr (Operation == detail::PlanOperation::Update)
255 static_assert(std::tuple_size_v<Assignments> != 0,
256 "ORM_QUERY_UPDATE_ASSIGNMENTS: an update plan requires SET");
257 }
258 template <typename... Args>
259 auto toDynamic(Args&&... values) const
260 {
262 detail::validateParameters<StaticPlan, Args...>();
263 const auto args = std::forward_as_tuple(values...);
264 if constexpr (Operation == detail::PlanOperation::Remove)
265 return detail::bindExpression(std::get<0>(state), args);
266 else if constexpr (Operation == detail::PlanOperation::Update)
267 {
268 orm::Update<Model> result;
269 std::apply([&](const auto&... assignment) { (detail::applyAssignment(result, assignment, args), ...); },
270 std::get<5>(state));
271 result.where(detail::bindExpression(std::get<0>(state), args));
272 return result;
273 }
274 else
275 {
276 auto result = [&]
277 {
278 if constexpr (isProjection)
279 {
281 std::apply([&](const auto&... projection) { output.project(projection...); },
282 std::get<4>(state));
283 return output;
284 }
285 else
286 return orm::Query<Model>{};
287 }();
288 if constexpr (hasPredicate)
289 result.where(detail::bindExpression(std::get<0>(state), args));
290 std::apply([&](const auto&... order) { result.orderBy(order...); }, std::get<1>(state));
291 std::apply([&](const auto&... group) { result.groupBy(group...); }, std::get<2>(state));
292 if constexpr (hasHaving)
293 result.having(detail::bindExpression(std::get<3>(state), args));
294 if constexpr (Distinct)
295 result.distinct();
296 if constexpr (!Join)
297 result.disableJoining();
298 if constexpr (hasLimit)
299 result.limit(paginationValue(std::get<6>(state), args));
300 if constexpr (hasOffset)
301 result.offset(paginationValue(std::get<7>(state), args));
302 if constexpr (!isProjection)
303 std::apply([&](const auto&... include)
304 { (result.template include<std::remove_cvref_t<decltype(include)>::member>(), ...); },
305 std::get<8>(state));
306 return result;
307 }
308 }
309
310 private:
311 friend struct detail::PlanAccess;
312 constexpr explicit StaticPlan(State data) : state{std::move(data)} {}
313 template <std::size_t Index, typename V>
314 constexpr auto replace(V value) const
315 {
316 auto newState = [&]<std::size_t... I>(std::index_sequence<I...>)
317 {
318 auto element = [&]<std::size_t N>()
319 {
320 if constexpr (N == Index)
321 return value;
322 else
323 return std::get<N>(state);
324 };
325 return std::tuple { element.template operator()<I>()... };
326 }(std::make_index_sequence<std::tuple_size_v<State>>{});
327 return detail::PlanAccess::make<StaticPlan<Operation, Model, Result, decltype(newState), Distinct, Join>>(
328 std::move(newState));
329 }
330 template <typename V, typename A>
331 static auto paginationValue(const V& value, const A& args) -> std::size_t
332 {
333 const auto result = detail::resolveValue(value, args);
334 if (result > static_cast<std::size_t>(std::numeric_limits<long long>::max()))
335 throw std::out_of_range{"Pagination exceeds the supported signed 64-bit range"};
336 return result;
337 }
338 State state;
339 };
340}
341namespace detail
342{
343using EmptyPlanState = std::tuple<NoClause, std::tuple<>, std::tuple<>, NoClause, std::tuple<>, std::tuple<>, NoClause,
344 NoClause, std::tuple<>>;
345template <PlanOperation O, typename M, typename R, typename S, bool D, bool J>
346inline constexpr bool isStaticPlan<StaticPlan<O, M, R, S, D, J>> = true;
347template <typename P>
348concept StaticPlanType = isStaticPlan<std::remove_cvref_t<P>>;
349}
350export
351{
352 // namespace detail
354 template <typename Model>
355 constexpr auto select()
356 {
357 return detail::PlanAccess::make<
359 }
360 template <typename Source, typename Result, typename... P>
361// requires detail::ORM_QUERY_MODEL_PROJECTIONS<Source, P...> &&
362// detail::ORM_QUERY_UUID_PROJECTION_DOMAINS<Result, P...>
363 constexpr auto selectAs(P... projections)
364 {
365 static_assert(sizeof...(P) > 0, "ORM_QUERY_PROJECTION: a projection plan requires projected fields");
366 using State = std::tuple<detail::NoClause, std::tuple<>, std::tuple<>, detail::NoClause, std::tuple<P...>,
367 std::tuple<>, detail::NoClause, detail::NoClause, std::tuple<>>;
368 return detail::PlanAccess::make<StaticPlan<detail::PlanOperation::Select, Source, Result, State>>(
369 State{{}, {}, {}, {}, std::tuple{std::move(projections)...}, {}, {}, {}, {}});
371 template <typename Model>
372 constexpr auto update()
373 {
374 return detail::PlanAccess::make<
375 StaticPlan<detail::PlanOperation::Update, Model, Model, detail::EmptyPlanState>>(detail::EmptyPlanState{});
377 template <typename Model>
378 constexpr auto remove()
379 {
380 return detail::PlanAccess::make<
381 StaticPlan<detail::PlanOperation::Remove, Model, Model, detail::EmptyPlanState>>(detail::EmptyPlanState{});
382 }
383}
384} // namespace orm::query
A select query that returns a user-defined DTO instead of the full source model.
auto project(Projections... projections) -> ProjectionQuery< Source, Result > &
A template class representing a select query in the ORM framework.
Definition select.cppm:39
auto where(const P &predicate) -> Update< T > &
Definition update.cppm:72
static consteval auto validateShape() -> void
std::tuple_element_t< 4, State > Projections
constexpr auto having(P predicate) const
std::tuple_element_t< 7, State > Offset
constexpr auto disableJoining() const
std::tuple_element_t< 6, State > Limit
constexpr auto project(P... projections) const
constexpr auto offset(std::size_t value) const
constexpr auto where(P predicate) const
constexpr auto orderBy(O... orders) const
constexpr auto orHaving(P predicate) const
std::tuple_element_t< 3, State > Having
constexpr auto andWhere(P predicate) const
static constexpr bool isDistinct
static constexpr bool shouldJoin
static constexpr bool hasPredicate
constexpr auto groupBy(C... columns) const
std::tuple_element_t< 5, State > Assignments
std::tuple_element_t< 1, State > Orders
detail::ParameterTypes< State > ParameterTypes
std::tuple_element_t< 8, State > Includes
constexpr auto distinct() const
static constexpr bool hasLimit
std::tuple_element_t< 0, State > Predicate
constexpr auto limit(std::size_t value) const
static constexpr bool hasOffset
constexpr auto include() const
static constexpr bool hasHaving
constexpr auto set(TypedColumn< Members... >, V &&value) const
auto toDynamic(Args &&... values) const
std::tuple_element_t< 2, State > Groups
static constexpr auto operation
static constexpr bool isProjection
constexpr auto orWhere(P predicate) const
constexpr auto andHaving(P predicate) const
orm::query::detail::Column Column
constexpr bool isNullable
Definition mapping.cppm:552
constexpr auto select()
constexpr auto update()
constexpr auto remove()
constexpr auto selectAs(P... projections)