ORM C++
Loading...
Searching...
No Matches
emitter.cppm
Go to the documentation of this file.
1module;
2
3#include <algorithm>
4#include <cstddef>
5#include <optional>
6#include <span>
7#include <stdexcept>
8#include <string>
9#include <string_view>
10#include <utility>
11#include <vector>
12
13export module orm:sql_emitter;
14
15import :foundation;
16import :model;
17import :expressions;
18import :sql_contracts;
19import :sql_program;
20
21namespace orm::db
22{
23namespace detail
24{
25template <CompiledSqlFlavor Flavor>
26struct StaticSqlPolicy
27{
28 [[nodiscard]] constexpr auto isSqlite() const noexcept -> bool
29 {
30 return Flavor == CompiledSqlFlavor::SQLite;
31 }
32 [[nodiscard]] constexpr auto quoteIdentifier(std::string_view name) const -> std::string
33 {
34 return quoteStandardIdentifier(name, Flavor);
35 }
36 [[nodiscard]] constexpr auto bindMarker(std::string_view name) const -> std::string
37 {
38 if (!isPortableBindName(name))
39 throw std::invalid_argument{"Invalid SQL bind parameter name"};
40 return sqlConcat(":", name);
41 }
42 [[nodiscard]] constexpr auto renderAggregateResult(std::string_view value, bool exact) const -> std::string
43 {
44 if constexpr (Flavor == CompiledSqlFlavor::PostgreSQL)
45 {
46 if (exact)
47 return sqlConcat("CAST(", value, " AS TEXT)");
48 }
49 if constexpr (Flavor == CompiledSqlFlavor::MySQLFamily)
50 {
51 if (exact)
52 return sqlConcat("CAST(", value, " AS CHAR)");
53 }
54 return std::string{value};
55 }
56 [[nodiscard]] constexpr auto pagination(const SqlQueryView& query) const -> std::string
57 {
58 std::string result;
59 if (query.hasLimit)
60 {
61 result += " LIMIT ";
62 result += query.boundPagination ? bindMarker(parameterName(query.bindings[query.limitParameter])) :
63 decimal(query.literalLimit);
64 }
65 else if constexpr (Flavor == CompiledSqlFlavor::SQLite)
66 {
67 if (query.hasOffset)
68 result += " LIMIT -1";
69 }
70 else if constexpr (Flavor == CompiledSqlFlavor::MySQLFamily)
71 {
72 if (query.hasOffset)
73 result += " LIMIT 18446744073709551615";
74 }
75 if (query.hasOffset)
76 {
77 result += " OFFSET ";
78 result += query.boundPagination ? bindMarker(parameterName(query.bindings[query.offsetParameter])) :
79 decimal(query.literalOffset);
80 }
81 return result;
82 }
83};
84
85struct RuntimeSqlPolicy
86{
87 const SqlDialect& dialect;
89 [[nodiscard]] constexpr auto isSqlite() const noexcept -> bool
90 {
91 return backend == BackendType::Sqlite;
92 }
93 [[nodiscard]] auto quoteIdentifier(std::string_view name) const -> std::string
94 {
95 return dialect.quoteIdentifier(name);
96 }
97 [[nodiscard]] auto bindMarker(std::string_view name) const -> std::string
98 {
99 return dialect.bindMarker(name);
100 }
101 [[nodiscard]] auto renderAggregateResult(std::string_view value, bool exact) const -> std::string
102 {
103 return dialect.renderAggregateResult(value, exact);
104 }
105 [[nodiscard]] auto pagination(const SqlQueryView& query) const -> std::string
106 {
107 if (query.boundPagination)
108 throw std::logic_error{"A runtime dialect requires literal pagination"};
109 return dialect.renderPagination(
110 PaginationSpec{.limit = query.hasLimit ? std::optional{query.literalLimit} : std::nullopt,
111 .offset = query.hasOffset ? std::optional{query.literalOffset} : std::nullopt,
112 .hasOrderBy = !query.orders.empty()});
113 }
114};
115
116[[nodiscard]] constexpr auto sqlPath(const SqlSource& source) -> std::string
117{
118 if (source.pathSize == 0)
119 return {};
120 return source.pathSize == 1 ? std::string{source.pathParts[0]} :
121 sqlConcat(source.pathParts[0], ".", source.pathParts[1]);
122}
123[[nodiscard]] constexpr auto parseSqlSource(std::string_view path) -> SqlSource
124{
125 SqlSource result;
126 std::size_t start = 0;
127 while (start <= path.size())
128 {
129 const auto dot = path.find('.', start);
130 const auto part = path.substr(start, dot - start);
131 if (part.empty())
132 throw std::invalid_argument{sqlConcat("Column path contains an empty segment: ", path)};
133 if (result.pathSize == result.pathParts.size())
134 throw std::invalid_argument{sqlConcat("Only one level of related model paths is supported: ", path)};
135 result.pathParts[result.pathSize++] = part;
136 if (dot == std::string_view::npos)
137 break;
138 start = dot + 1;
139 }
140 return result;
141}
142[[nodiscard]] constexpr auto requireSqlColumn(model::ModelView model, std::string_view name) -> const model::ColumnView&
143{
144 const auto* column = model.findColumn(name);
145 if (column == nullptr)
146 throw std::invalid_argument{sqlConcat("Unknown column path segment: ", name)};
147 return *column;
148}
149[[nodiscard]] constexpr auto requireSqlTarget(model::ModelView model,
150 const model::ColumnView& column) -> model::ModelView
151{
152 if (column.kind != model::FieldKind::ToOne)
153 throw std::invalid_argument{sqlConcat("Column is not a related model: ", column.fieldName)};
154 const auto target = model.resolveTarget(column);
155 if (!target)
156 throw std::logic_error{"To-one relation target is not available in the schema"};
157 return target;
158}
159[[nodiscard]] constexpr auto sqlPrimaryKey(model::ModelView model) -> std::vector<const model::ColumnView*>
160{
161 std::vector<const model::ColumnView*> result;
162 for (const auto& column : model->columns)
163 if (column.isPrimaryKey)
164 {
165 if (column.kind == model::FieldKind::ToOne)
166 throw std::invalid_argument{"Relations with model-valued primary-key fields are not supported"};
167 result.push_back(&column);
168 }
169 if (result.empty())
170 throw std::invalid_argument{"Collection relation endpoint must define a primary key"};
171 return result;
172}
173struct SqlColumnInfo
174{
175 const model::ColumnView* column{};
176 const model::ColumnView* relation{};
177 model::ColumnType logicalType{};
178 bool isNotNull{};
179};
180[[nodiscard]] constexpr auto resolveSqlColumn(const SqlSource& source, model::ModelView model,
181 bool write = false) -> SqlColumnInfo
182{
183 if (source.pathSize == 1)
184 {
185 const auto& column = requireSqlColumn(model, source.pathParts[0]);
186 if (column.kind == model::FieldKind::ToOne)
187 throw std::invalid_argument{sqlConcat(write ?
188 "Use a related primary-key field path in write queries: " :
189 "Use a related field path instead of the related model itself: ",
190 sqlPath(source))};
191 return {&column, nullptr, column.type.value(), column.isNotNull};
192 }
193 if (source.pathSize == 2)
194 {
195 const auto& relation = requireSqlColumn(model, source.pathParts[0]);
196 const auto target = requireSqlTarget(model, relation);
197 const auto& column = requireSqlColumn(target, source.pathParts[1]);
198 if (write && !column.isPrimaryKey)
199 throw std::invalid_argument{
200 sqlConcat("Only related primary-key fields can be used in write queries: ", sqlPath(source))};
201 return {&column, &relation, column.type.value(), relation.isNotNull};
202 }
203 throw std::invalid_argument{sqlConcat("Only one level of related model paths is supported: ", sqlPath(source))};
204}
205
206// Resolve physical UUID representation from the actual field, after SQL shape
207// construction and before any parameter is exchanged with the backend.
208inline auto applyUuidBindingStorage(const SqlQueryView& query, model::ModelView model, BackendType backend,
209 std::span<StatementParameter> parameters) -> void
210{
211 std::vector<std::optional<model::UuidStorage>> assigned(parameters.size());
212 const auto annotate = [&](std::size_t index, const SqlSource& source, model::ModelView scope)
213 {
214 if (index >= query.bindings.size())
215 throw std::logic_error{"SQL binding index is out of range"};
216 const auto name = parameterName(query.bindings[index]);
217 const auto found =
218 std::ranges::find_if(parameters, [&](const auto& parameter) { return parameter.name == name; });
219 if (found == parameters.end())
220 throw std::logic_error{"SQL binding has no matching parameter"};
221 if (found->getLogicalType() == model::ColumnType::Uuid)
222 {
223 const auto column = resolveSqlColumn(source, scope);
224 if (column.logicalType == model::ColumnType::Uuid)
225 {
226 const auto storage = column.column->uuidStorage(backend);
227 const auto parameterIndex = static_cast<std::size_t>(found - parameters.begin());
228 if (assigned[parameterIndex] && *assigned[parameterIndex] != storage)
229 throw std::invalid_argument{"A SQL parameter has conflicting UUID representations"};
230 assigned[parameterIndex] = storage;
231 found->uuidStorage = storage;
232 }
233 }
234 };
235
236 for (const auto& assignment : query.assignments)
237 annotate(assignment.parameter, assignment.source, model);
238
239 const auto visit = [&](const auto& self, std::size_t index, model::ModelView scope) -> void
240 {
241 if (index == noSqlNode)
242 return;
243 if (index >= query.nodes.size())
244 throw std::logic_error{"SQL predicate index is out of range"};
245 const auto& node = query.nodes[index];
246 if (node.kind == SqlNodeKind::Comparison || node.kind == SqlNodeKind::List || node.kind == SqlNodeKind::Between)
247 {
248 for (std::size_t i = 0; i < node.parameterCount; ++i)
249 annotate(node.firstParameter + i, node.source, scope);
250 }
251 else if (node.kind == SqlNodeKind::And || node.kind == SqlNodeKind::Or)
252 {
253 self(self, node.left, scope);
254 self(self, node.right, scope);
255 }
256 else if (node.kind == SqlNodeKind::Not)
257 self(self, node.left, scope);
258 else if (node.kind == SqlNodeKind::Collection && node.left != noSqlNode)
259 {
260 const auto* relation = scope.findRelation(node.relation);
261 if (relation == nullptr)
262 throw std::invalid_argument{"Unknown collection relation"};
263 const auto target = scope.resolveTarget(*relation);
264 if (!target)
265 throw std::invalid_argument{"Collection relation target is not available"};
266 self(self, node.left, target);
267 }
268 };
269 visit(visit, query.predicate, model);
270 visit(visit, query.having, model);
271}
272
273struct SqlRenderScope
274{
275 model::ModelView model;
276 bool shouldJoin = true;
277 bool write{};
278 bool allowCollections = true;
279 std::string tableAlias;
280 std::vector<std::pair<std::string, std::string>> relationAliases;
281};
282template <typename Policy>
283[[nodiscard]] constexpr auto sqlQualified(const Policy& policy, std::string_view qualifier,
284 std::string_view name) -> std::string
285{
286 return sqlConcat(policy.quoteIdentifier(qualifier), ".", policy.quoteIdentifier(name));
287}
288template <typename Policy>
289[[nodiscard]] constexpr auto emitSqlColumn(const SqlSource& source, const SqlRenderScope& scope, const Policy& policy,
290 bool qualify = true) -> std::string
291{
292 const auto info = resolveSqlColumn(source, scope.model, scope.write);
293 const auto root = scope.tableAlias.empty() ? scope.model->tableName : std::string_view{scope.tableAlias};
294 if (info.relation == nullptr)
295 return qualify ? sqlQualified(policy, root, info.column->name) : policy.quoteIdentifier(info.column->name);
296 if (scope.write || !scope.shouldJoin)
297 {
298 if (!info.column->isPrimaryKey)
299 throw std::invalid_argument{
300 sqlConcat("Cannot filter by non-id related field when joining is disabled: ", sqlPath(source))};
301 const auto name = sqlConcat(info.relation->name, "_", info.column->name);
302 return qualify ? sqlQualified(policy, root, name) : policy.quoteIdentifier(name);
303 }
304 auto qualifier = info.relation->name;
305 for (const auto& entry : scope.relationAliases)
306 if (entry.first == qualifier)
307 {
308 qualifier = entry.second;
309 break;
310 }
311 return sqlQualified(policy, qualifier, info.column->name);
312}
313[[nodiscard]] constexpr auto sqlComparison(unsigned operation) -> std::string_view
314{
315 using enum query::detail::ComparisonOperator;
316 switch (static_cast<query::detail::ComparisonOperator>(operation))
317 {
318 case Equal:
319 return "=";
320 case NotEqual:
321 return "!=";
322 case Greater:
323 return ">";
324 case GreaterOrEqual:
325 return ">=";
326 case Less:
327 return "<";
328 case LessOrEqual:
329 return "<=";
330 case Like:
331 return "LIKE";
332 case NotLike:
333 return "NOT LIKE";
334 }
335 throw std::invalid_argument{"Unsupported comparison operator"};
336}
337[[nodiscard]] constexpr auto sqlAggregateName(query::detail::AggregateFunction function) -> std::string_view
338{
339 using enum query::detail::AggregateFunction;
340 switch (function)
341 {
342 case Count:
343 case CountAll:
344 return "COUNT";
345 case Sum:
346 return "SUM";
347 case Avg:
348 return "AVG";
349 case Min:
350 return "MIN";
351 case Max:
352 return "MAX";
353 }
354 throw std::invalid_argument{"Unsupported aggregate function"};
355}
356template <typename Policy>
357[[nodiscard]] constexpr auto emitSqlSource(const SqlSource& source, const SqlRenderScope& scope, const Policy& policy,
358 bool projection = false) -> std::string
359{
360 if (!source.isAggregate)
361 return emitSqlColumn(source, scope, policy);
362 auto result = sqlConcat(sqlAggregateName(source.function), "(");
363 result +=
364 source.function == query::detail::AggregateFunction::CountAll ? "*" : emitSqlColumn(source, scope, policy);
365 result += ')';
366 return projection ?
367 policy.renderAggregateResult(result, source.function == query::detail::AggregateFunction::Sum ||
368 source.function == query::detail::AggregateFunction::Avg) :
369 result;
370}
371[[nodiscard]] constexpr auto hasSqlAlias(const std::vector<std::string>& names, std::string_view name) -> bool
372{
373 return std::ranges::find(names, name) != names.end();
374}
375[[nodiscard]] constexpr auto uniqueSqlAlias(std::string_view base, const std::vector<std::string>& names) -> std::string
376{
377 std::string result{base};
378 std::size_t suffix = 1;
379 while (hasSqlAlias(names, result))
380 result = sqlConcat(base, "_", decimal(suffix++));
381 return result;
382}
383template <typename Policy>
384[[nodiscard]] constexpr auto emitSqlJoins(const SqlRenderScope& scope, const Policy& policy) -> std::string
385{
386 std::string result;
387 for (const auto& relation : scope.model->columns)
388 {
389 if (relation.kind != model::FieldKind::ToOne)
390 continue;
391 const auto target = requireSqlTarget(scope.model, relation);
392 auto alias = std::string{relation.name};
393 for (const auto& entry : scope.relationAliases)
394 if (entry.first == relation.name)
395 {
396 alias = entry.second;
397 break;
398 }
399 result += sqlConcat(" LEFT JOIN ", policy.quoteIdentifier(target->tableName), " AS ",
400 policy.quoteIdentifier(alias), " ON ");
401 bool first = true;
402 for (const auto& column : target->columns)
403 if (column.isPrimaryKey)
404 {
405 if (!first)
406 result += " AND ";
407 first = false;
408 const auto root =
409 scope.tableAlias.empty() ? scope.model->tableName : std::string_view{scope.tableAlias};
410 result += sqlConcat(sqlQualified(policy, alias, column.name), " = ",
411 sqlQualified(policy, root, sqlConcat(relation.name, "_", column.name)));
412 }
413 if (scope.allowCollections)
414 result += ' ';
415 }
416 if (scope.allowCollections && !result.empty())
417 result.pop_back();
418 return result;
419}
420
421template <typename Policy>
422[[nodiscard]] constexpr auto emitSqlPredicate(const SqlQueryView& query, std::size_t index, const SqlRenderScope& scope,
423 const Policy& policy) -> std::string;
424template <typename Policy>
425[[nodiscard]] constexpr auto emitSqlCollection(const SqlQueryView& query, const SqlNode& node,
426 const SqlRenderScope& scope, const Policy& policy) -> std::string
427{
428 if (!scope.allowCollections)
429 throw std::invalid_argument{"Nested collection predicates are not supported"};
430 const auto* relation = scope.model.findRelation(node.relation);
431 if (relation == nullptr || relation->kind == model::RelationKind::ToOne)
432 throw std::invalid_argument{sqlConcat("Unknown collection relation: ", node.relation)};
433 if (node.operation != static_cast<unsigned>(query::detail::CollectionOperator::Exists) && node.left == noSqlNode)
434 throw std::invalid_argument{"Collection any/none requires an element predicate"};
435 const auto ownerKeys = sqlPrimaryKey(scope.model);
436 const auto target = scope.model.resolveTarget(*relation);
437 if (!target)
438 throw std::logic_error{"Collection relation target is not available in the schema"};
439 const auto targetKeys = sqlPrimaryKey(target);
440 // Choose the name as a view before constructing the owning string. MSVC 14.52
441 // Debug can lose track of the temporary string's lifetime in constant evaluation.
442 const std::string outer{scope.tableAlias.empty() ? scope.model->tableName : std::string_view{scope.tableAlias}};
443 std::vector<std::string> reserved{outer};
444 for (const auto& column : target->columns)
445 if (column.kind == model::FieldKind::ToOne)
446 reserved.emplace_back(column.name);
447 const auto targetAlias = uniqueSqlAlias("orm_relation_target", reserved);
448 reserved.push_back(targetAlias);
449 const auto junctionAlias = uniqueSqlAlias("orm_relation_junction", reserved);
450 reserved.push_back(junctionAlias);
451 std::vector<std::string> assigned{outer, targetAlias, junctionAlias};
452 SqlRenderScope nested{target, true, false, false, targetAlias, {}};
453 for (const auto& column : target->columns)
454 if (column.kind == model::FieldKind::ToOne)
455 {
456 std::string alias{column.name};
457 if (hasSqlAlias(assigned, column.name))
458 alias = uniqueSqlAlias(column.name, reserved);
459 nested.relationAliases.emplace_back(column.name, alias);
460 assigned.push_back(alias);
461 reserved.push_back(alias);
462 }
463 std::string from;
464 std::string predicate;
465 if (relation->kind == model::RelationKind::OneToMany)
466 {
467 const auto* mapped = target.findRelation(relation->mappedBy);
468 if (mapped == nullptr || mapped->kind != model::RelationKind::ToOne)
469 throw std::invalid_argument{sqlConcat("Invalid OneToMany mappedBy relation: ", relation->fieldName)};
470 for (const auto* key : ownerKeys)
471 {
472 if (!predicate.empty())
473 predicate += " AND ";
474 predicate += sqlConcat(sqlQualified(policy, targetAlias, sqlConcat(mapped->columnName, "_", key->name)),
475 " = ", sqlQualified(policy, outer, key->name));
476 }
477 from = sqlConcat(policy.quoteIdentifier(target->tableName), " AS ", policy.quoteIdentifier(targetAlias),
478 emitSqlJoins(nested, policy));
479 }
480 else
481 {
482 const auto junction = scope.model.resolveJunction(*relation);
483 if (!junction.isConfigured())
484 throw std::invalid_argument{
485 sqlConcat("ManyToMany relation has no junction mapping: ", relation->fieldName)};
486 if (junction.ownerColumns.size() != ownerKeys.size() || junction.targetColumns.size() != targetKeys.size())
487 throw std::invalid_argument{
488 sqlConcat("Junction columns do not match relation endpoint keys: ", junction.tableName)};
489 for (std::size_t i = 0; i < ownerKeys.size(); ++i)
490 {
491 if (!predicate.empty())
492 predicate += " AND ";
493 predicate += sqlConcat(sqlQualified(policy, junctionAlias, junction.ownerColumns[i]), " = ",
494 sqlQualified(policy, outer, ownerKeys[i]->name));
495 }
496 std::string targetJoin;
497 for (std::size_t i = 0; i < targetKeys.size(); ++i)
498 {
499 if (!targetJoin.empty())
500 targetJoin += " AND ";
501 targetJoin += sqlConcat(sqlQualified(policy, targetAlias, targetKeys[i]->name), " = ",
502 sqlQualified(policy, junctionAlias, junction.targetColumns[i]));
503 }
504 from = sqlConcat(policy.quoteIdentifier(junction.tableName), " AS ", policy.quoteIdentifier(junctionAlias),
505 " JOIN ", policy.quoteIdentifier(target->tableName), " AS ",
506 policy.quoteIdentifier(targetAlias), " ON ", targetJoin, emitSqlJoins(nested, policy));
507 }
508 if (node.left != noSqlNode)
509 predicate += sqlConcat(" AND ", emitSqlPredicate(query, node.left, nested, policy));
510 const auto exists = sqlConcat("EXISTS (SELECT 1 FROM ", from, " WHERE ", predicate, ")");
511 return node.operation == static_cast<unsigned>(query::detail::CollectionOperator::None) ?
512 sqlConcat("NOT (", exists, ")") :
513 exists;
514}
515template <typename Policy>
516[[nodiscard]] constexpr auto emitSqlPredicate(const SqlQueryView& query, std::size_t index, const SqlRenderScope& scope,
517 const Policy& policy) -> std::string
518{
519 const auto& node = query.nodes[index];
520 auto bind = [&](std::size_t offset)
521 { return policy.bindMarker(parameterName(query.bindings[node.firstParameter + offset])); };
522 switch (node.kind)
523 {
524 case SqlNodeKind::Comparison:
525 if (node.source.isAggregate && node.operation >= static_cast<unsigned>(query::detail::ComparisonOperator::Like))
526 throw std::invalid_argument{"Unsupported aggregate comparison operator"};
527 return sqlConcat(emitSqlSource(node.source, scope, policy), " ", sqlComparison(node.operation), " ", bind(0));
528 case SqlNodeKind::Null:
529 return sqlConcat(emitSqlColumn(node.source, scope, policy),
530 node.operation == static_cast<unsigned>(query::detail::NullOperator::IsNull) ? " IS NULL" :
531 " IS NOT NULL");
532 case SqlNodeKind::List:
533 {
534 const auto in = node.operation == static_cast<unsigned>(query::detail::ListOperator::In);
535 if (node.parameterCount == 0)
536 return std::string{in ? "(1 = 0)" : "(1 = 1)"};
537 auto result = sqlConcat(emitSqlColumn(node.source, scope, policy), in ? " IN (" : " NOT IN (");
538 for (std::size_t i = 0; i < node.parameterCount; ++i)
539 {
540 if (i != 0)
541 result += ", ";
542 result += bind(i);
543 }
544 result += ')';
545 return result;
546 }
547 case SqlNodeKind::Between:
548 return sqlConcat(emitSqlColumn(node.source, scope, policy),
549 node.operation == static_cast<unsigned>(query::detail::BetweenOperator::Between) ?
550 " BETWEEN " :
551 " NOT BETWEEN ",
552 bind(0), " AND ", bind(1));
553 case SqlNodeKind::And:
554 case SqlNodeKind::Or:
555 return sqlConcat("(", emitSqlPredicate(query, node.left, scope, policy),
556 node.kind == SqlNodeKind::And ? " AND " : " OR ",
557 emitSqlPredicate(query, node.right, scope, policy), ")");
558 case SqlNodeKind::Not:
559 return sqlConcat("(NOT (", emitSqlPredicate(query, node.left, scope, policy), "))");
560 case SqlNodeKind::Raw:
561 return std::string{node.rawSql};
562 case SqlNodeKind::Collection:
563 return emitSqlCollection(query, node, scope, policy);
564 case SqlNodeKind::Invalid:
565 break;
566 }
567 throw std::logic_error{"Unknown SQL predicate node"};
568}
569template <typename Policy>
570[[nodiscard]] constexpr auto emitSqlFullFields(const SqlRenderScope& scope, const Policy& policy) -> std::string
571{
572 std::string result;
573 std::string storageClasses;
574 auto append = [&](std::string expression, std::string alias, const model::ColumnView& column)
575 {
576 if (!result.empty())
577 result += ", ";
578 result += sqlConcat(expression, " AS ", policy.quoteIdentifier(alias));
579 if (policy.isSqlite() && column.type == model::ColumnType::Uuid &&
580 column.uuidStorage(BackendType::Sqlite) != model::UuidStorage::Native)
581 storageClasses += sqlConcat(", typeof(", expression, ")");
582 };
583 for (const auto& column : scope.model->columns)
584 {
585 if (column.kind == model::FieldKind::Scalar)
586 append(sqlQualified(policy, scope.model->tableName, column.name),
587 sqlConcat(scope.model->tableName, "_", column.name), column);
588 else
589 {
590 const auto target = requireSqlTarget(scope.model, column);
591 for (const auto& child : target->columns)
592 if (scope.shouldJoin)
593 append(sqlQualified(policy, column.name, child.name), sqlConcat(column.name, "_", child.name),
594 child);
595 else if (child.isPrimaryKey)
596 append(sqlQualified(policy, scope.model->tableName, sqlConcat(column.name, "_", child.name)),
597 sqlConcat(scope.model->tableName, "_", column.name, "_", child.name), child);
598 }
599 }
600 return result + storageClasses;
601}
602template <typename Policy>
603[[nodiscard]] constexpr auto emitSql(const SqlQueryView& query, model::ModelView model,
604 const Policy& policy) -> std::string
605{
606 SqlRenderScope scope{model, query.shouldJoin, query.operation != SqlOperation::Select, true, {}, {}};
607 std::string result;
608 if (query.operation == SqlOperation::Select)
609 {
610 result = query.isDistinct ? "SELECT DISTINCT " : "SELECT ";
611 if (query.projections.empty())
612 result += emitSqlFullFields(scope, policy);
613 else
614 {
615 std::string storageClasses;
616 for (std::size_t i = 0; i < query.projections.size(); ++i)
617 {
618 if (i != 0)
619 result += ", ";
620 result += sqlConcat(emitSqlSource(query.projections[i].source, scope, policy, true), " AS ",
621 policy.quoteIdentifier(query.projections[i].alias));
622 const auto& source = query.projections[i].source;
623 if (policy.isSqlite() && !source.isAggregate)
624 {
625 const auto info = resolveSqlColumn(source, model);
626 if (info.logicalType == model::ColumnType::Uuid &&
627 info.column->uuidStorage(BackendType::Sqlite) != model::UuidStorage::Native)
628 storageClasses += sqlConcat(", typeof(", emitSqlSource(source, scope, policy, true), ")");
629 }
630 }
631 result += storageClasses;
632 }
633 result += sqlConcat(" FROM ", policy.quoteIdentifier(model->tableName));
634 if (query.shouldJoin)
635 result += emitSqlJoins(scope, policy);
636 }
637 else if (query.operation == SqlOperation::Update)
638 {
639 if (query.assignments.empty())
640 throw std::invalid_argument{"UPDATE requires at least one assignment"};
641 if (query.predicate == noSqlNode)
642 throw std::invalid_argument{"UPDATE requires a WHERE predicate"};
643 result = sqlConcat("UPDATE ", policy.quoteIdentifier(model->tableName), " SET ");
644 for (std::size_t i = 0; i < query.assignments.size(); ++i)
645 {
646 if (i != 0)
647 result += ", ";
648 const auto& assignment = query.assignments[i];
649 result += sqlConcat(emitSqlColumn(assignment.source, scope, policy, false), " = ",
650 policy.bindMarker(parameterName(query.bindings[assignment.parameter])));
651 }
652 }
653 else
654 result = sqlConcat("DELETE FROM ", policy.quoteIdentifier(model->tableName));
655 if (query.predicate != noSqlNode)
656 result += sqlConcat(" WHERE ", emitSqlPredicate(query, query.predicate, scope, policy));
657 if (!query.groups.empty())
658 {
659 result += " GROUP BY ";
660 for (std::size_t i = 0; i < query.groups.size(); ++i)
661 {
662 if (i != 0)
663 result += ", ";
664 result += emitSqlColumn(query.groups[i], scope, policy);
665 }
666 }
667 if (query.having != noSqlNode)
668 result += sqlConcat(" HAVING ", emitSqlPredicate(query, query.having, scope, policy));
669 if (!query.orders.empty())
670 {
671 result += " ORDER BY ";
672 for (std::size_t i = 0; i < query.orders.size(); ++i)
673 {
674 if (i != 0)
675 result += ", ";
676 const auto& order = query.orders[i];
677 result += order.isRaw ? std::string{order.rawSql} :
678 sqlConcat(emitSqlColumn(order.source, scope, policy),
679 order.direction == query::detail::OrderDirection::Asc ? " ASC" : " DESC");
680 }
681 }
682 result += policy.pagination(query);
683 result += ';';
684 return result;
685}
686} // namespace detail
687} // namespace orm::db
BackendType
Definition types.cppm:62
constexpr auto exists()
Definition columns.cppm:463