27namespace orm::query::detail
31using namespace orm::db::detail;
33template <
typename Tuple,
typename Callback>
34constexpr auto visitTypes(Callback&& callback) ->
void
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>>{});
41consteval auto source() -> SqlSource
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;
53 result.pathSize = E::pathParts.size();
54 for (std::size_t i = 0; i < result.pathSize; ++i)
55 result.pathParts[i] = E::pathParts[i];
59template <
typename Value>
60constexpr auto addBinding(SqlProgram& program) -> std::size_t
62 const auto index = program.bindings.size();
63 program.bindings.push_back({model::LogicalTypeTraits<Value>::value, index, {}});
67constexpr auto appendExpression(SqlProgram& program) -> std::size_t
73 node.source = source<typename E::Source>();
74 node.operation =
static_cast<unsigned>(E::operation);
75 node.firstParameter = program.bindings.size();
78 node.kind = SqlNodeKind::Comparison;
79 node.parameterCount = 1;
82 node.kind = SqlNodeKind::Null;
85 node.kind = SqlNodeKind::Between;
86 node.parameterCount = 2;
90 node.kind = SqlNodeKind::List;
91 node.parameterCount = E::arity;
94 for (std::size_t i = 0; i < node.parameterCount; ++i)
95 (
void)addBinding<typename E::Source::Value>(program);
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);
105 node.kind = SqlNodeKind::Not;
106 node.left = appendExpression<typename E::Child>(program);
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);
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);
122template <
typename Tuple>
124template <
typename... Items>
125struct TupleEligible<std::tuple<Items...>> : std::bool_constant<(staticSqlEligible<Items> && ...)>
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;
134constexpr auto program() -> SqlProgram
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>(
142 result.assignments.push_back({source<typename A::Source>(), addBinding<typename A::Source::Value>(result)});
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);
166[[nodiscard]]
consteval auto validSource(
const SqlSource& value, model::ModelView model,
bool write,
bool joins) ->
bool
168 if (value.isAggregate && value.function == AggregateFunction::CountAll)
170 if (value.pathSize == 0 || value.pathSize > 2)
172 const auto* column = model.findColumn(value.pathParts[0]);
173 if (column ==
nullptr)
175 if (value.pathSize == 1)
179 const auto target = model.resolveTarget(*column);
182 const auto* child = target.findColumn(value.pathParts[1]);
184 (!(write || !joins) || child->isPrimaryKey);
186[[nodiscard]]
consteval auto validKeys(model::ModelView model) ->
bool
189 for (
const auto& column : model->columns)
190 if (column.isPrimaryKey)
198[[nodiscard]]
consteval auto validNode(
const SqlQueryView& view, std::size_t index, model::ModelView model,
bool write,
199 bool joins,
bool collectionAllowed =
true) ->
bool
201 if (index == noSqlNode)
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))
213 const auto* relation = model.findRelation(node.relation);
216 const auto target = model.resolveTarget(*relation);
217 if (!target || !validKeys(target))
221 const auto* mapped = target.findRelation(relation->mappedBy);
227 const auto junction = model.resolveJunction(*relation);
228 if (!junction.isConfigured() || junction.ownerColumns.size() != model.primaryKeySize() ||
229 junction.targetColumns.size() != target.primaryKeySize())
232 if (node.operation !=
static_cast<unsigned>(CollectionOperator::Exists) && node.left == noSqlNode)
234 for (
const auto& column : target->columns)
237 const auto child = target.resolveTarget(column);
238 if (!child || !validKeys(child))
241 return validNode(view, node.left, target,
false,
true,
false);
243template <db::CompiledSqlFlavor Flavor>
244struct CheckingPolicy : db::detail::StaticSqlPolicy<Flavor>
247 [[nodiscard]]
constexpr auto quoteIdentifier(std::string_view name)
const -> std::string
249 if (name.empty() || name.find(
'\0') != std::string_view::npos ||
252 std::ranges::count_if(name, [](
unsigned char c) { return (c & 0xc0) != 0x80; }) > 64))
255 std::string result(1, quote);
256 for (
const auto character : name)
258 if (character == quote)
266template <
typename Schema,
typename P, db::CompiledSqlFlavor Flavor>
267consteval auto valid() ->
bool
269 const auto data = program<P>();
270 const auto view = data.view();
272 const auto write = P::operation != PlanOperation::Select;
273 if constexpr (P::operation == PlanOperation::Update)
274 if (data.assignments.empty() || view.predicate == noSqlNode)
276 if constexpr (P::operation == PlanOperation::Remove)
277 if (view.predicate == noSqlNode)
279 if (!validNode(view, view.predicate, model, write, view.shouldJoin) ||
280 !validNode(view, view.having, model,
false, view.shouldJoin))
282 for (
const auto& item : view.groups)
283 if (!validSource(item, model,
false, view.shouldJoin))
285 for (
const auto& item : view.orders)
286 if (!validSource(item.source, model,
false, view.shouldJoin))
288 for (
const auto& item : view.projections)
289 if (!validSource(item.source, model,
false, view.shouldJoin))
291 for (
const auto& item : view.assignments)
292 if (!validSource(item.source, model,
true,
false))
294 for (
const auto& column : model->columns)
298 (void)emitSql(view, model, CheckingPolicy<Flavor>{{}, &result});
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>
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;
317 bool shouldJoin =
true;
320 std::size_t limitParameter{};
321 std::size_t offsetParameter{};
322 [[nodiscard]]
constexpr auto view() const -> SqlQueryView
324 return {operation, nodes, predicate, having, orders, groups, projections,
325 assignments, includes, bindings, isDistinct, shouldJoin, hasLimit, hasOffset,
326 true, limitParameter, offsetParameter, 0, 0};
330consteval auto freeze()
332 constexpr auto sizes = []()
consteval
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()};
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;
358template <
typename Frozen, std::
size_t Length>
359struct CompiledStatement
362 std::array<char, Length + 1> sql{};
364 [[nodiscard]]
constexpr auto view() const -> std::string_view
366 return {sql.data(), Length};
369template <
typename Schema,
typename P, db::CompiledSqlFlavor Flavor>
370consteval auto compile()
372 constexpr bool accepted = valid<Schema, P, Flavor>();
373 constexpr auto length = []()
consteval
375 if constexpr (accepted)
377 auto data = program<P>();
379 db::detail::StaticSqlPolicy<Flavor>{})
383 return std::size_t{};
385 using Frozen =
decltype(freeze<P>());
386 CompiledStatement<Frozen, length> result;
387 result.program = freeze<P>();
388 result.valid = accepted;
389 if constexpr (accepted)
392 db::detail::StaticSqlPolicy<Flavor>{});
393 std::ranges::copy(value, result.sql.begin());
400inline constexpr bool compiledSqlEligible = compiled::eligible<P>;
401template <
typename Schema,
typename P, db::CompiledSqlFlavor Flavor>
403inline constexpr auto compiledStatement = compiled::compile<Schema, P, Flavor>();
405template <
typename P,
typename Args>
407auto collectParameters(
const P& plan,
const Args& args) -> std::vector<db::StatementParameter>
409 std::vector<db::StatementParameter> result;
410 const auto& state = PlanAccess::get(plan);
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});
419 [&](
const auto&... assignment)
421 [[maybe_unused]]
auto add = [&]<
typename A>(
const A& item)
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);
431 if (value.has_value())
432 append(typedValue<typename C::Value>(*value), type);
434 append(std::nullopt, type);
437 append(typedValue<typename C::Value>(value), type);
439 (add(assignment), ...);
442 auto addValue = [&](QueryValue value)
444 const auto type = value.getLogicalType();
445 append(std::move(value), type);
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)
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});
458 if constexpr (P::hasLimit)
459 addPagination(std::get<6>(state));
460 if constexpr (P::hasOffset)
461 addPagination(std::get<7>(state));
constexpr bool isNullable
constexpr auto modelView() noexcept -> ModelView
consteval auto logicalType() -> model::ColumnType