ORM C++
Loading...
Searching...
No Matches
compiled.cppm
Go to the documentation of this file.
1module;
2
3#include <algorithm>
4#include <array>
5#include <concepts>
6#include <cstddef>
7#include <limits>
8#include <optional>
9#include <stdexcept>
10#include <string>
11#include <string_view>
12#include <tuple>
13#include <type_traits>
14#include <utility>
15#include <vector>
16
17export module orm:sql_compiled;
18
19import :foundation;
20import :model;
21import :expressions;
22import :static_plan;
23import :sql_contracts;
24import :sql_program;
25import :sql_emitter;
26
27namespace orm::query::detail
28{
29namespace compiled
30{
31using namespace orm::db::detail;
32
33template <typename Tuple, typename Callback>
34constexpr auto visitTypes(Callback&& callback) -> void
35{
36 [&]<std::size_t... I>(std::index_sequence<I...>) {
37 (callback.template operator()<std::tuple_element_t<I, Tuple>>(), ...);
38 }(std::make_index_sequence<std::tuple_size_v<Tuple>>{});
39}
40template <typename E>
41consteval auto source() -> SqlSource
42{
43 SqlSource result;
44 if constexpr (E::kind == ExprKind::Aggregate)
45 {
46 if constexpr (!std::same_as<typename E::Source, void>)
47 result = source<typename E::Source>();
48 result.isAggregate = true;
49 result.function = E::function;
50 }
51 else
52 {
53 result.pathSize = E::pathParts.size();
54 for (std::size_t i = 0; i < result.pathSize; ++i)
55 result.pathParts[i] = E::pathParts[i];
56 }
57 return result;
58}
59template <typename Value>
60constexpr auto addBinding(SqlProgram& program) -> std::size_t
61{
62 const auto index = program.bindings.size();
63 program.bindings.push_back({model::LogicalTypeTraits<Value>::value, index, {}});
64 return index;
65}
66template <typename E>
67constexpr auto appendExpression(SqlProgram& program) -> std::size_t
68{
69 SqlNode node;
70 if constexpr (E::kind == ExprKind::Comparison || E::kind == ExprKind::Null || E::kind == ExprKind::List ||
71 E::kind == ExprKind::Between)
72 {
73 node.source = source<typename E::Source>();
74 node.operation = static_cast<unsigned>(E::operation);
75 node.firstParameter = program.bindings.size();
76 if constexpr (E::kind == ExprKind::Comparison)
77 {
78 node.kind = SqlNodeKind::Comparison;
79 node.parameterCount = 1;
80 }
81 else if constexpr (E::kind == ExprKind::Null)
82 node.kind = SqlNodeKind::Null;
83 else if constexpr (E::kind == ExprKind::Between)
84 {
85 node.kind = SqlNodeKind::Between;
86 node.parameterCount = 2;
87 }
88 else
89 {
90 node.kind = SqlNodeKind::List;
91 node.parameterCount = E::arity;
92 }
93 if constexpr (E::kind != ExprKind::Null)
94 for (std::size_t i = 0; i < node.parameterCount; ++i)
95 (void)addBinding<typename E::Source::Value>(program);
96 }
97 else if constexpr (E::kind == ExprKind::Logical)
98 {
99 node.kind = E::operation == LogicalOperator::And ? SqlNodeKind::And : SqlNodeKind::Or;
100 node.left = appendExpression<typename E::Left>(program);
101 node.right = appendExpression<typename E::Right>(program);
102 }
103 else if constexpr (E::kind == ExprKind::Not)
104 {
105 node.kind = SqlNodeKind::Not;
106 node.left = appendExpression<typename E::Child>(program);
107 }
108 else if constexpr (E::kind == ExprKind::Collection)
109 {
110 node.kind = SqlNodeKind::Collection;
111 node.operation = static_cast<unsigned>(E::operation);
112 node.relation = E::relationName;
113 if constexpr (!std::same_as<typename E::Child, void>)
114 node.left = appendExpression<typename E::Child>(program);
115 }
116 else
117 static_assert(sizeof(E) == 0, "ORM_QUERY_STATIC_SQL: expression is not eligible for compiled SQL");
118 const auto index = program.nodes.size();
119 program.nodes.push_back(node);
120 return index;
121}
122template <typename Tuple>
123struct TupleEligible;
124template <typename... Items>
125struct TupleEligible<std::tuple<Items...>> : std::bool_constant<(staticSqlEligible<Items> && ...)>
126{
127};
128template <typename P>
129inline constexpr bool eligible =
130 (!P::hasPredicate || staticSqlEligible<typename P::Predicate>) &&
131 (!P::hasHaving || staticSqlEligible<typename P::Having>) && TupleEligible<typename P::Orders>::value &&
132 TupleEligible<typename P::Projections>::value;
133template <typename P>
134constexpr auto program() -> SqlProgram
135{
136 SqlProgram result;
137 result.operation = static_cast<SqlOperation>(P::operation);
138 result.shouldJoin = P::operation == PlanOperation::Select && P::shouldJoin;
139 result.isDistinct = P::isDistinct;
140 visitTypes<typename P::Assignments>(
141 [&]<typename A>() {
142 result.assignments.push_back({source<typename A::Source>(), addBinding<typename A::Source::Value>(result)});
143 });
144 if constexpr (P::hasPredicate)
145 result.predicate = appendExpression<typename P::Predicate>(result);
146 visitTypes<typename P::Groups>([&]<typename C>() { result.groups.push_back(source<C>()); });
147 if constexpr (P::hasHaving)
148 result.having = appendExpression<typename P::Having>(result);
149 visitTypes<typename P::Orders>(
150 [&]<typename O>() { result.orders.push_back({source<typename O::Source>(), O::direction, false, {}}); });
151 visitTypes<typename P::Projections>(
152 [&]<typename Projection>()
153 { result.projections.push_back({source<typename Projection::Source>(), Projection::alias.view()}); });
154 visitTypes<typename P::Includes>(
155 [&]<typename I>() { result.includes.push_back(model::detail::reflectedMemberNameStorage<I::member>.view()); });
156 result.hasLimit = P::hasLimit;
157 result.hasOffset = P::hasOffset;
158 result.boundPagination = true;
159 if constexpr (P::hasLimit)
160 result.limitParameter = addBinding<std::size_t>(result);
161 if constexpr (P::hasOffset)
162 result.offsetParameter = addBinding<std::size_t>(result);
163 return result;
164}
165
166[[nodiscard]] consteval auto validSource(const SqlSource& value, model::ModelView model, bool write, bool joins) -> bool
167{
168 if (value.isAggregate && value.function == AggregateFunction::CountAll)
169 return true;
170 if (value.pathSize == 0 || value.pathSize > 2)
171 return false;
172 const auto* column = model.findColumn(value.pathParts[0]);
173 if (column == nullptr)
174 return false;
175 if (value.pathSize == 1)
176 return column->kind == model::FieldKind::Scalar && column->type.has_value();
177 if (column->kind != model::FieldKind::ToOne)
178 return false;
179 const auto target = model.resolveTarget(*column);
180 if (!target)
181 return false;
182 const auto* child = target.findColumn(value.pathParts[1]);
183 return child != nullptr && child->kind == model::FieldKind::Scalar && child->type.has_value() &&
184 (!(write || !joins) || child->isPrimaryKey);
185}
186[[nodiscard]] consteval auto validKeys(model::ModelView model) -> bool
187{
188 bool found = false;
189 for (const auto& column : model->columns)
190 if (column.isPrimaryKey)
191 {
192 if (column.kind != model::FieldKind::Scalar)
193 return false;
194 found = true;
195 }
196 return found;
197}
198[[nodiscard]] consteval auto validNode(const SqlQueryView& view, std::size_t index, model::ModelView model, bool write,
199 bool joins, bool collectionAllowed = true) -> bool
200{
201 if (index == noSqlNode)
202 return true;
203 const auto& node = view.nodes[index];
204 if (node.kind == SqlNodeKind::And || node.kind == SqlNodeKind::Or)
205 return validNode(view, node.left, model, write, joins, collectionAllowed) &&
206 validNode(view, node.right, model, write, joins, collectionAllowed);
207 if (node.kind == SqlNodeKind::Not)
208 return validNode(view, node.left, model, write, joins, collectionAllowed);
209 if (node.kind != SqlNodeKind::Collection)
210 return validSource(node.source, model, write, joins);
211 if (!collectionAllowed || !validKeys(model))
212 return false;
213 const auto* relation = model.findRelation(node.relation);
214 if (relation == nullptr || relation->kind == model::RelationKind::ToOne)
215 return false;
216 const auto target = model.resolveTarget(*relation);
217 if (!target || !validKeys(target))
218 return false;
219 if (relation->kind == model::RelationKind::OneToMany)
220 {
221 const auto* mapped = target.findRelation(relation->mappedBy);
222 if (mapped == nullptr || mapped->kind != model::RelationKind::ToOne)
223 return false;
224 }
225 else
226 {
227 const auto junction = model.resolveJunction(*relation);
228 if (!junction.isConfigured() || junction.ownerColumns.size() != model.primaryKeySize() ||
229 junction.targetColumns.size() != target.primaryKeySize())
230 return false;
231 }
232 if (node.operation != static_cast<unsigned>(CollectionOperator::Exists) && node.left == noSqlNode)
233 return false;
234 for (const auto& column : target->columns)
235 if (column.kind == model::FieldKind::ToOne)
236 {
237 const auto child = target.resolveTarget(column);
238 if (!child || !validKeys(child))
239 return false;
240 }
241 return validNode(view, node.left, target, false, true, false);
242}
243template <db::CompiledSqlFlavor Flavor>
244struct CheckingPolicy : db::detail::StaticSqlPolicy<Flavor>
245{
246 bool* valid;
247 [[nodiscard]] constexpr auto quoteIdentifier(std::string_view name) const -> std::string
248 {
249 if (name.empty() || name.find('\0') != std::string_view::npos ||
250 (Flavor == db::CompiledSqlFlavor::PostgreSQL && name.size() > 63) ||
252 std::ranges::count_if(name, [](unsigned char c) { return (c & 0xc0) != 0x80; }) > 64))
253 *valid = false;
254 const auto quote = Flavor == db::CompiledSqlFlavor::MySQLFamily ? '`' : '"';
255 std::string result(1, quote);
256 for (const auto character : name)
257 {
258 if (character == quote)
259 result += quote;
260 result += character;
261 }
262 result += quote;
263 return result;
264 }
265};
266template <typename Schema, typename P, db::CompiledSqlFlavor Flavor>
267consteval auto valid() -> bool
268{
269 const auto data = program<P>();
270 const auto view = data.view();
271 constexpr auto model = model::modelView<Schema, typename P::Model>();
272 const auto write = P::operation != PlanOperation::Select;
273 if constexpr (P::operation == PlanOperation::Update)
274 if (data.assignments.empty() || view.predicate == noSqlNode)
275 return false;
276 if constexpr (P::operation == PlanOperation::Remove)
277 if (view.predicate == noSqlNode)
278 return false;
279 if (!validNode(view, view.predicate, model, write, view.shouldJoin) ||
280 !validNode(view, view.having, model, false, view.shouldJoin))
281 return false;
282 for (const auto& item : view.groups)
283 if (!validSource(item, model, false, view.shouldJoin))
284 return false;
285 for (const auto& item : view.orders)
286 if (!validSource(item.source, model, false, view.shouldJoin))
287 return false;
288 for (const auto& item : view.projections)
289 if (!validSource(item.source, model, false, view.shouldJoin))
290 return false;
291 for (const auto& item : view.assignments)
292 if (!validSource(item.source, model, true, false))
293 return false;
294 for (const auto& column : model->columns)
295 if (column.kind == model::FieldKind::ToOne && !model.resolveTarget(column))
296 return false;
297 bool result = true;
298 (void)emitSql(view, model, CheckingPolicy<Flavor>{{}, &result});
299 return result;
300}
301
302template <std::size_t Nodes, std::size_t Orders, std::size_t Groups, std::size_t Projections, std::size_t Assignments,
303 std::size_t Includes, std::size_t Bindings>
304struct FrozenProgram
305{
306 std::array<SqlNode, Nodes> nodes{};
307 std::array<SqlOrder, Orders> orders{};
308 std::array<SqlSource, Groups> groups{};
309 std::array<SqlProjection, Projections> projections{};
310 std::array<SqlAssignment, Assignments> assignments{};
311 std::array<std::string_view, Includes> includes{};
312 std::array<SqlBindingDescriptor, Bindings> bindings{};
313 SqlOperation operation{};
314 std::size_t predicate = noSqlNode;
315 std::size_t having = noSqlNode;
316 bool isDistinct{};
317 bool shouldJoin = true;
318 bool hasLimit{};
319 bool hasOffset{};
320 std::size_t limitParameter{};
321 std::size_t offsetParameter{};
322 [[nodiscard]] constexpr auto view() const -> SqlQueryView
323 {
324 return {operation, nodes, predicate, having, orders, groups, projections,
325 assignments, includes, bindings, isDistinct, shouldJoin, hasLimit, hasOffset,
326 true, limitParameter, offsetParameter, 0, 0};
327 }
328};
329template <typename P>
330consteval auto freeze()
331{
332 constexpr auto sizes = []() consteval
333 {
334 auto data = program<P>();
335 return std::array{data.nodes.size(), data.orders.size(), data.groups.size(), data.projections.size(),
336 data.assignments.size(), data.includes.size(), data.bindings.size()};
337 }();
338 FrozenProgram<sizes[0], sizes[1], sizes[2], sizes[3], sizes[4], sizes[5], sizes[6]> result;
339 const auto data = program<P>();
340 std::ranges::copy(data.nodes, result.nodes.begin());
341 std::ranges::copy(data.orders, result.orders.begin());
342 std::ranges::copy(data.groups, result.groups.begin());
343 std::ranges::copy(data.projections, result.projections.begin());
344 std::ranges::copy(data.assignments, result.assignments.begin());
345 std::ranges::copy(data.includes, result.includes.begin());
346 std::ranges::copy(data.bindings, result.bindings.begin());
347 result.operation = data.operation;
348 result.predicate = data.predicate;
349 result.having = data.having;
350 result.isDistinct = data.isDistinct;
351 result.shouldJoin = data.shouldJoin;
352 result.hasLimit = data.hasLimit;
353 result.hasOffset = data.hasOffset;
354 result.limitParameter = data.limitParameter;
355 result.offsetParameter = data.offsetParameter;
356 return result;
357}
358template <typename Frozen, std::size_t Length>
359struct CompiledStatement
360{
361 Frozen program{};
362 std::array<char, Length + 1> sql{};
363 bool valid{};
364 [[nodiscard]] constexpr auto view() const -> std::string_view
365 {
366 return {sql.data(), Length};
367 }
368};
369template <typename Schema, typename P, db::CompiledSqlFlavor Flavor>
370consteval auto compile()
371{
372 constexpr bool accepted = valid<Schema, P, Flavor>();
373 constexpr auto length = []() consteval
374 {
375 if constexpr (accepted)
376 {
377 auto data = program<P>();
378 return emitSql(data.view(), model::modelView<Schema, typename P::Model>(),
379 db::detail::StaticSqlPolicy<Flavor>{})
380 .size();
381 }
382 else
383 return std::size_t{};
384 }();
385 using Frozen = decltype(freeze<P>());
386 CompiledStatement<Frozen, length> result;
387 result.program = freeze<P>();
388 result.valid = accepted;
389 if constexpr (accepted)
390 {
391 const auto value = emitSql(result.program.view(), model::modelView<Schema, typename P::Model>(),
392 db::detail::StaticSqlPolicy<Flavor>{});
393 std::ranges::copy(value, result.sql.begin());
394 }
395 return result;
396}
397} // namespace compiled
398
399template <typename P>
400inline constexpr bool compiledSqlEligible = compiled::eligible<P>;
401template <typename Schema, typename P, db::CompiledSqlFlavor Flavor>
402// requires compiledSqlEligible<P>
403inline constexpr auto compiledStatement = compiled::compile<Schema, P, Flavor>();
404
405template <typename P, typename Args>
406// requires compiledSqlEligible<P>
407auto collectParameters(const P& plan, const Args& args) -> std::vector<db::StatementParameter>
408{
409 std::vector<db::StatementParameter> result;
410 const auto& state = PlanAccess::get(plan);
411 auto append = [&](std::optional<QueryValue> value, model::ColumnType logicalType)
412 {
413 const auto nullType = value.has_value() ? std::optional<model::ColumnType>{} : std::optional{logicalType};
414 result.push_back({.name = db::detail::parameterName({logicalType, result.size(), {}}),
415 .value = std::move(value),
416 .nullType = nullType});
417 };
418 std::apply(
419 [&](const auto&... assignment)
420 {
421 [[maybe_unused]] auto add = [&]<typename A>(const A& item)
422 {
423 using C = typename A::Source;
424 const auto& value = resolveValue(item.value, args);
425 constexpr auto type = model::LogicalTypeTraits<typename C::Value>::value;
426 using V = std::remove_cvref_t<decltype(value)>;
427 if constexpr (std::same_as<V, std::nullopt_t> || std::same_as<V, std::nullptr_t>)
428 append(std::nullopt, type);
429 else if constexpr (model::isNullable<V>)
430 {
431 if (value.has_value())
432 append(typedValue<typename C::Value>(*value), type);
433 else
434 append(std::nullopt, type);
435 }
436 else
437 append(typedValue<typename C::Value>(value), type);
438 };
439 (add(assignment), ...);
440 },
441 std::get<5>(state));
442 auto addValue = [&](QueryValue value)
443 {
444 const auto type = value.getLogicalType();
445 append(std::move(value), type);
446 };
447 if constexpr (P::hasPredicate)
448 visitValues(std::get<0>(state), args, addValue);
449 if constexpr (P::hasHaving)
450 visitValues(std::get<3>(state), args, addValue);
451 [[maybe_unused]] auto addPagination = [&](const auto& stored)
452 {
453 const auto value = static_cast<std::size_t>(resolveValue(stored, args));
454 if (value > static_cast<std::size_t>(std::numeric_limits<long long>::max()))
455 throw std::out_of_range{"Pagination exceeds the supported signed 64-bit range"};
456 addValue(QueryValue{value});
457 };
458 if constexpr (P::hasLimit)
459 addPagination(std::get<6>(state));
460 if constexpr (P::hasOffset)
461 addPagination(std::get<7>(state));
462 return result;
463}
464} // namespace orm::query::detail
constexpr bool isNullable
Definition mapping.cppm:552
constexpr auto modelView() noexcept -> ModelView
Definition schema.cppm:120
consteval auto logicalType() -> model::ColumnType
Definition mapping.cppm:602