ORM C++
Loading...
Searching...
No Matches
columns.cppm
Go to the documentation of this file.
1module;
2
3#include <array>
4#include <concepts>
5#include <cstddef>
6#include <optional>
7#include <string_view>
8#include <tuple>
9#include <type_traits>
10#include <utility>
11
12export module orm:model_columns;
13
14import orm.reflection;
15import :foundation;
16import :model_mapping;
17import :model_views;
18
19// model/StaticModel.hpp
20namespace orm::model
21{
22export
23{
24
25 template <typename... Models>
26 struct Schema;
27
28 /** A physical UUID representation for one field and backend. */
29 template <auto Member, db::BackendType Backend, UuidStorage Storage>
30// requires std::is_member_object_pointer_v<decltype(Member)>
32 {
33 inline static constexpr auto member = Member;
34 inline static constexpr auto backend = Backend;
35 inline static constexpr auto storage = Storage;
36 static_assert(Backend == db::BackendType::Mysql || Backend == db::BackendType::Sqlite,
37 "ORM_MODEL_UUID_STORAGE: storage overrides are supported for MySQL and SQLite only");
38 static_assert(Storage == UuidStorage::Native || Storage == UuidStorage::Binary16 ||
39 Storage == UuidStorage::Text36,
40 "ORM_MODEL_UUID_STORAGE: invalid UUID storage representation");
41 };
42
43 template <typename... Definitions>
44 struct UuidStorages
45 {
46 template <typename Model>
47 [[nodiscard]] static consteval auto isValidFor() -> bool
48 {
49 if constexpr (not(std::same_as<detail::member_owner_t<Definitions::member>, Model> && ...))
50 return false;
51 else
52 {
53 constexpr std::array<db::BackendType, sizeof...(Definitions)> backends{Definitions::backend...};
54 // The same member may be declared once per backend, so only a repeated
55 // (member, backend) pair is a conflict. Mirror `uniqueMemberNames` here:
56 // capture the names into a tuple and view the stored lvalues, because
57 // `.view()` on the prvalue from `reflectedMemberName` selects the deleted
58 // `const&&` overload, and a `constexpr` tuple is rejected outright.
59 const auto nameStorage = std::tuple{detail::reflectedMemberName<Definitions::member>()...};
60 const auto names = [&]<std::size_t... I>(std::index_sequence<I...>) consteval {
61 return std::array<std::string_view, sizeof...(Definitions)>{std::get<I>(nameStorage).view()...};
62 }(std::make_index_sequence<sizeof...(Definitions)>{});
63 for (std::size_t left = 0; left < names.size(); ++left)
64 for (std::size_t right = left + 1; right < names.size(); ++right)
65 if (names[left] == names[right] && backends[left] == backends[right])
66 return false;
67 return (detail::memberExists<Model, Definitions::member>() && ...) &&
68 ((orm::UuidDomainValue<
69 detail::static_optional_value_t<detail::member_value_t<Definitions::member>>>) &&
70 ...);
71 }
72 }
74 [[nodiscard]] consteval auto find(std::string_view name, db::BackendType backend) const -> UuidStorage
75 {
76 auto result = UuidStorage::Native;
77 ((detail::reflectedMemberName<Definitions::member>() == name && Definitions::backend == backend ?
78 static_cast<void>(result = Definitions::storage) :
79 static_cast<void>(0)),
80 ...);
81 return result;
82 }
83 };
84}
85namespace detail
86{
87template <typename>
88struct IsUuidStorages : std::false_type
89{
90};
91
92template <typename... Definitions>
93struct IsUuidStorages<UuidStorages<Definitions...>> : std::true_type
94{
95};
96
97template <typename Model>
98consteval auto hasValidUuidStorageDefinition() -> bool
99{
100 if constexpr (requires { Model::uuid_storage; })
101 {
102 using definition_t = std::remove_cvref_t<decltype(Model::uuid_storage)>;
103 if constexpr (IsUuidStorages<definition_t>::value)
104 return definition_t::template isValidFor<Model>();
105 else
106 return false;
107 }
108 else
109 return true;
110}
111
112template <typename Model>
113consteval auto mappedUuidStorage(std::string_view name, db::BackendType backend) -> UuidStorage
114{
115 if constexpr (requires { Model::uuid_storage; })
116 {
117 using definition_t = std::remove_cvref_t<decltype(Model::uuid_storage)>;
118 if constexpr (IsUuidStorages<definition_t>::value && definition_t::template isValidFor<Model>())
119 return Model::uuid_storage.find(name, backend);
120 }
121 return UuidStorage::Native;
122}
123
124template <typename>
125struct StaticSchemaTraits;
126
127template <typename... Models>
128struct StaticSchemaTraits<Schema<Models...>>
129{
130 template <typename Model>
131 inline static constexpr bool contains = (std::same_as<Model, Models> || ...);
132
133 template <typename Model, std::size_t... Is>
134 [[nodiscard]] static consteval auto indexOfImpl(std::index_sequence<Is...>) -> std::size_t
135 {
136 std::size_t result = 0;
137 (void)(((std::same_as<Model, Models>) ? (result = Is, true) : false) || ...);
138 return result;
139 }
140
141 template <typename Model>
142 [[nodiscard]] static consteval auto indexOf() -> std::size_t
143 {
144 static_assert(contains<Model>, "ORM_SCHEMA_MODEL_MISSING: requested model type does not belong to this schema");
145 return indexOfImpl<Model>(std::make_index_sequence<sizeof...(Models)>{});
146 }
147};
148
149template <typename>
150struct IsFixedString : std::false_type
151{
152};
153
154template <std::size_t Size>
155struct IsFixedString<reflection::FixedString<Size>> : std::true_type
156{
157};
158
159template <typename>
160struct IsColumnNames : std::false_type
161{
162};
163
164template <typename... Definitions>
165struct IsColumnNames<ColumnNames<Definitions...>> : std::true_type
166{
167};
168
169template <typename>
170struct IsPrimaryKey : std::false_type
171{
172};
173
174template <typename>
175struct IsStringLengths : std::false_type
176{
177};
178
179template <typename... Definitions>
180struct IsStringLengths<StringLengths<Definitions...>> : std::true_type
181{
182};
183
184template <typename Model>
185consteval auto hasValidStringLengthsDefinition() -> bool
186{
187 if constexpr (requires { Model::string_lengths; })
188 {
189 using definition_t = std::remove_cvref_t<decltype(Model::string_lengths)>;
190 if constexpr (IsStringLengths<definition_t>::value)
191 return definition_t::template isValidFor<Model>();
192 else
193 return false;
194 }
195 else
196 return true;
197}
198
199template <typename Model>
200consteval auto mappedStringLength(std::string_view name) -> std::optional<std::size_t>
201{
202 if constexpr (requires { Model::string_lengths; })
203 {
204 using definition_t = std::remove_cvref_t<decltype(Model::string_lengths)>;
205 if constexpr (IsStringLengths<definition_t>::value)
206 return Model::string_lengths.find(name);
207 }
208 return std::nullopt;
209}
210
211template <auto... Members>
212struct IsPrimaryKey<PrimaryKey<Members...>> : std::true_type
213{
214};
215
216template <typename>
217struct IsAutoIncrement : std::false_type
218{
219};
220
221template <auto... Members>
222struct IsAutoIncrement<AutoIncrement<Members...>> : std::true_type
223{
224};
225
226template <typename>
227struct IsRelations : std::false_type
228{
229};
230
231template <typename... Descriptors>
232struct IsRelations<std::tuple<Descriptors...>>
233 : std::bool_constant<(orm::detail::IsRelationDescriptor<Descriptors>::value && ...)>
234{
235};
236
237template <typename Model>
238consteval auto hasValidTableNameDefinition() -> bool
239{
240 if constexpr (requires { Model::table_name; })
241 {
242 using definition_t = std::remove_cvref_t<decltype(Model::table_name)>;
243 if constexpr (IsFixedString<definition_t>::value)
244 {
245 return not Model::table_name.view().empty();
246 }
247 else
248 {
249 return false;
250 }
251 }
252 else
253 {
254 return true;
255 }
256}
257
258template <typename Model>
259consteval auto hasValidColumnNamesDefinition() -> bool
260{
261 if constexpr (requires { Model::columns_names; })
262 {
263 using definition_t = std::remove_cvref_t<decltype(Model::columns_names)>;
264 if constexpr (IsColumnNames<definition_t>::value)
265 {
266 return definition_t::template isValidFor<Model>();
267 }
268 else
269 {
270 return false;
271 }
272 }
273 else
274 {
275 return true;
276 }
277}
278
279template <typename Model>
280consteval auto hasValidPrimaryKeyDefinition() -> bool
281{
282 if constexpr (requires { Model::id_columns; })
283 {
284 using definition_t = std::remove_cvref_t<decltype(Model::id_columns)>;
285 if constexpr (IsPrimaryKey<definition_t>::value)
286 {
287 return definition_t::template isValidFor<Model>();
288 }
289 else
290 {
291 return false;
292 }
293 }
294 else
295 {
296 return true;
297 }
298}
299
300template <typename Model>
301consteval auto hasValidAutoIncrementDefinition() -> bool
302{
303 if constexpr (requires { Model::auto_increment_columns; })
304 {
305 using definition_t = std::remove_cvref_t<decltype(Model::auto_increment_columns)>;
306 if constexpr (IsAutoIncrement<definition_t>::value)
307 {
308 return definition_t::template isValidFor<Model>();
309 }
310 else
311 {
312 return false;
313 }
314 }
315 else
316 {
317 return true;
318 }
319}
320
321template <typename Model>
322consteval auto normalizedDefaultTableName()
323{
324 constexpr auto source = reflection::typeNameStorage<Model>.view();
325 constexpr auto prefixSize = source.starts_with("class ") ? std::string_view{"class "}.size() :
326 source.starts_with("struct ") ? std::string_view{"struct "}.size() :
327 0U;
328 constexpr auto resultSize = [source]
329 {
330 std::size_t result{};
331 for (std::size_t index = prefixSize; index < source.size(); ++index)
332 {
333 ++result;
334 if (source[index] == ':' && index + 1 < source.size() && source[index + 1] == ':')
335 {
336 ++index;
337 }
338 }
339 return result;
340 }();
341
342 std::array<char, resultSize + 1> result{};
343 std::size_t output{};
344 for (std::size_t index = prefixSize; index < source.size(); ++index)
345 {
346 if (source[index] == ':' && index + 1 < source.size() && source[index + 1] == ':')
347 {
348 result[output++] = '_';
349 ++index;
350 }
351 else
352 {
353 result[output++] = source[index];
354 }
355 }
356 return result;
357}
358
359template <typename Model>
360inline constexpr auto defaultTableNameStorage = normalizedDefaultTableName<Model>();
361
362template <typename Model>
363consteval auto modelTypeName() -> std::string_view
364{
366}
367
368template <typename Model>
369consteval auto mappedTableName() -> std::string_view
370{
371 if constexpr (requires { Model::table_name; })
372 {
373 using definition_t = std::remove_cvref_t<decltype(Model::table_name)>;
374 if constexpr (IsFixedString<definition_t>::value)
375 {
376 return Model::table_name.view();
377 }
378 }
379 constexpr auto& storage = defaultTableNameStorage<Model>;
380 return std::string_view{storage.data(), storage.size() - 1};
381}
382
383template <typename Model>
384consteval auto mappedColumnName(std::string_view fieldName) -> std::string_view
385{
386 if constexpr (requires { Model::columns_names; })
387 {
388 using definition_t = std::remove_cvref_t<decltype(Model::columns_names)>;
389 if constexpr (IsColumnNames<definition_t>::value && definition_t::template isValidFor<Model>())
390 {
391 if (const auto mapped = Model::columns_names.find(fieldName); mapped.has_value())
392 {
393 return mapped.value();
394 }
395 }
396 }
397 return fieldName;
398}
399
400template <typename Model>
401consteval auto isPrimaryKey(std::string_view fieldName) -> bool
402{
403 if constexpr (requires { Model::id_columns; })
404 {
405 using definition_t = std::remove_cvref_t<decltype(Model::id_columns)>;
406 if constexpr (IsPrimaryKey<definition_t>::value && definition_t::template isValidFor<Model>())
407 {
408 return Model::id_columns.contains(fieldName);
409 }
410 return false;
411 }
412 else
413 {
414 return fieldName.compare("id") == 0;
415 }
416}
417
418template <typename Model>
419consteval auto isAutoIncrement(std::string_view fieldName) -> bool
420{
421 if constexpr (requires { Model::auto_increment_columns; })
422 {
423 using definition_t = std::remove_cvref_t<decltype(Model::auto_increment_columns)>;
424 if constexpr (IsAutoIncrement<definition_t>::value && definition_t::template isValidFor<Model>())
425 {
426 return Model::auto_increment_columns.contains(fieldName);
427 }
428 return false;
429 }
430 else
431 {
432 return false;
433 }
434}
435
436template <typename Model, std::size_t... Indices>
437consteval auto hasDefaultPrimaryKey(std::index_sequence<Indices...>) -> bool
438{
439 return (((reflectedFieldName<Model, Indices>().compare("id") == 0) &&
442 ...);
443}
444
445template <typename Model>
446consteval auto hasPrimaryKey() -> bool
447{
448 if constexpr (requires { Model::id_columns; })
449 {
450 using definition_t = std::remove_cvref_t<decltype(Model::id_columns)>;
451 if constexpr (IsPrimaryKey<definition_t>::value)
452 {
453 return definition_t::size != 0 && definition_t::template isValidFor<Model>();
454 }
455 else
456 {
457 return false;
458 }
459 }
460 else
461 {
462 return hasDefaultPrimaryKey<Model>(std::make_index_sequence<reflection::fieldCount<Model>>{});
463 }
464}
465
466template <typename Model, typename SchemaType, std::size_t Index>
467consteval auto makeColumn() -> ColumnView
468{
470 using value_t = std::remove_cv_t<static_optional_value_t<std::remove_cvref_t<field_t>>>;
471 constexpr auto fieldName = reflectedFieldName<Model, Index>();
473 "ORM_MODEL_OPTIONAL_COLLECTION: relation collections cannot be optional");
474
475 if constexpr (StaticSchemaTraits<SchemaType>::template contains<value_t>)
476 {
477 static_assert(hasPrimaryKey<value_t>(),
478 "ORM_RELATION_KEYLESS: every to-one target must define a valid primary key");
479 return ColumnView{
480 .fieldIndex = Index,
481 .fieldName = fieldName,
482 .name = mappedColumnName<Model>(fieldName),
483 .type = std::nullopt,
484 .kind = FieldKind::ToOne,
485 .targetModelIndex = StaticSchemaTraits<SchemaType>::template indexOf<value_t>(),
486 .isPrimaryKey = isPrimaryKey<Model>(fieldName),
487 .isAutoIncrement = isAutoIncrement<Model>(fieldName),
488 .isNotNull = not isNullable<field_t>,
489 .maxStringLength = std::nullopt,
490 };
491 }
492 else
493 {
494 return ColumnView{
495 .fieldIndex = Index,
496 .fieldName = fieldName,
497 .name = mappedColumnName<Model>(fieldName),
498 .type = logicalType<field_t>(),
499 .kind = FieldKind::Scalar,
500 .targetModelIndex = noTargetModel,
501 .isPrimaryKey = isPrimaryKey<Model>(fieldName),
502 .isAutoIncrement = isAutoIncrement<Model>(fieldName),
503 .isNotNull = not isNullable<field_t>,
504 .maxStringLength = mappedStringLength<Model>(fieldName),
505 .mysqlUuidStorage = mappedUuidStorage<Model>(fieldName, db::BackendType::Mysql),
506 .sqliteUuidStorage = mappedUuidStorage<Model>(fieldName, db::BackendType::Sqlite),
507 };
508 }
509}
510
511template <typename Model, std::size_t OutputIndex, std::size_t... FieldIndices>
512consteval auto columnFieldIndex(std::index_sequence<FieldIndices...>) -> std::size_t
513{
514 constexpr std::array fieldIndices{FieldIndices...};
515 constexpr std::array included{
518 std::size_t output{};
519 std::size_t result = reflection::fieldCount<Model>;
520 for (std::size_t index = 0; index < included.size(); ++index)
521 {
522 if (included[index])
523 {
524 if (output == OutputIndex)
525 {
526 result = fieldIndices[index];
527 break;
528 }
529 ++output;
530 }
531 }
532 return result;
533}
534
535template <typename Model, typename SchemaType, std::size_t... FieldIndices, std::size_t... OutputIndices>
536consteval auto makeColumnsDirect(std::index_sequence<FieldIndices...>, std::index_sequence<OutputIndices...>)
537{
538 return std::array<ColumnView, sizeof...(OutputIndices)>{
539 makeColumn<Model, SchemaType,
540 columnFieldIndex<Model, OutputIndices>(std::index_sequence<FieldIndices...>{})>()...};
541}
542
543template <typename Model, typename SchemaType, std::size_t... Indices>
544consteval auto makeColumns(std::index_sequence<Indices...> fields)
545{
547 "ORM_MODEL_OPTIONAL_COLLECTION: relation collections cannot be optional");
548 constexpr auto columnCount =
550 return makeColumnsDirect<Model, SchemaType>(fields, std::make_index_sequence<columnCount>{});
551}
552
553template <std::size_t Size>
554consteval auto hasValidColumnNames(const std::array<ColumnView, Size>& columns) -> bool
555{
556 bool valid = true;
557 for (std::size_t left = 0; left < columns.size() && valid; ++left)
558 {
559 if (columns[left].fieldName.empty() || columns[left].name.empty())
560 {
561 valid = false;
562 break;
563 }
564 for (std::size_t right = left + 1; right < columns.size() && valid; ++right)
565 {
566 if (columns[left].fieldName.compare(columns[right].fieldName) == 0 ||
567 columns[left].name.compare(columns[right].name) == 0 ||
568 columns[left].fieldName.compare(columns[right].name) == 0 ||
569 columns[left].name.compare(columns[right].fieldName) == 0)
570 {
571 valid = false;
572 break;
573 }
574 }
575 }
576 return valid;
577}
578
579template <std::size_t Size>
580consteval auto hasValidPrimaryKey(const std::array<ColumnView, Size>& columns) -> bool
581{
582 bool valid = true;
583 for (const auto& column : columns)
584 {
585 if (column.isPrimaryKey && (not column.isNotNull || column.kind != FieldKind::Scalar))
586 {
587 valid = false;
588 break;
589 }
590 }
591 return valid;
592}
593
594template <std::size_t Size>
595consteval auto hasValidAutoIncrement(const std::array<ColumnView, Size>& columns) -> bool
596{
597 std::size_t primaryKeyCount{};
598 std::size_t autoIncrementCount{};
599 const ColumnView* autoIncrementColumn{};
600
601 for (const auto& column : columns)
602 {
603 primaryKeyCount += column.isPrimaryKey ? 1U : 0U;
604 if (column.isAutoIncrement)
605 {
606 ++autoIncrementCount;
607 autoIncrementColumn = &column;
608 }
609 }
610
611 if (autoIncrementCount == 0)
612 {
613 return true;
614 }
615 return autoIncrementCount == 1 && primaryKeyCount == 1 && autoIncrementColumn->isPrimaryKey &&
616 autoIncrementColumn->isNotNull && autoIncrementColumn->kind == FieldKind::Scalar &&
617 autoIncrementColumn->type == ColumnType::Int;
618}
619
620template <typename Model>
621consteval auto modelPrimaryKeyCount() -> std::size_t
622{
623 if constexpr (requires { Model::id_columns; })
624 {
625 using definition_t = std::remove_cvref_t<decltype(Model::id_columns)>;
626 if constexpr (IsPrimaryKey<definition_t>::value)
627 {
628 return definition_t::size;
629 }
630 else
631 {
632 return 0;
633 }
634 }
635 else
636 {
637 return hasDefaultPrimaryKey<Model>(std::make_index_sequence<reflection::fieldCount<Model>>{}) ? 1U : 0U;
638 }
639}
640
641template <std::size_t ResultSize, std::size_t ColumnCount>
642consteval auto makePrimaryKeyIndices(const std::array<ColumnView, ColumnCount>& columns)
643{
644 std::array<std::size_t, ResultSize> result{};
645 std::size_t output{};
646 for (std::size_t index = 0; index < columns.size(); ++index)
647 {
648 if (columns[index].isPrimaryKey)
649 {
650 result[output++] = index;
651 }
652 }
653 return result;
654}
655
656template <typename Model, std::size_t ColumnCount>
657consteval auto makeModelPrimaryKeyIndices(const std::array<ColumnView, ColumnCount>& columns)
658{
659 if constexpr (requires { Model::id_columns; })
660 {
661 using definition_t = std::remove_cvref_t<decltype(Model::id_columns)>;
662 if constexpr (IsPrimaryKey<definition_t>::value && definition_t::template isValidFor<Model>())
663 {
664 constexpr auto fieldIndices = definition_t::template indices<Model>();
665 std::array<std::size_t, fieldIndices.size()> result{};
666 for (std::size_t keyIndex = 0; keyIndex < fieldIndices.size(); ++keyIndex)
667 {
668 bool found{};
669 for (std::size_t columnIndex = 0; columnIndex < columns.size(); ++columnIndex)
670 {
671 if (columns[columnIndex].fieldIndex == fieldIndices[keyIndex])
672 {
673 result[keyIndex] = columnIndex;
674 found = true;
675 break;
676 }
677 }
678 if (not found)
679 {
680 result[keyIndex] = columns.size();
681 }
682 }
683 return result;
684 }
685 else
686 {
687 return std::array<std::size_t, 0>{};
688 }
689 }
690 else
691 {
692 return makePrimaryKeyIndices<modelPrimaryKeyCount<Model>()>(columns);
693 }
694}
695
696template <typename Model, typename SchemaType>
697inline constexpr auto staticColumns =
698 makeColumns<Model, SchemaType>(std::make_index_sequence<reflection::fieldCount<Model>>{});
699
700template <typename Model, typename SchemaType>
701inline constexpr auto staticPrimaryKeyIndices = makeModelPrimaryKeyIndices<Model>(staticColumns<Model, SchemaType>);
702} // namespace detail
703} // namespace orm::model
704
705namespace orm
706{
707export
708{
709 template <auto Member, db::BackendType Backend, model::UuidStorage Storage>
710// requires std::is_member_object_pointer_v<decltype(Member)>
712 {
713 return {};
714 }
715
716 template <typename... Definitions>
717 consteval auto uuidStorages(Definitions...) -> model::UuidStorages<Definitions...>
718 {
719 return {};
720 }
721}
722} // namespace orm
std::vector< query::QueryValue > PrimaryKey
BackendType
Definition types.cppm:62
auto compare(const SchemaSnapshot &before, const SchemaSnapshot &after, const GenerationDecisions &decisions={}) -> SchemaDiff
consteval auto logicalType() -> ColumnType
Resolves a C++ field type to its logical database type at compile time. Users may extend the closed s...
Definition mapping.cppm:528
constexpr auto noTargetModel
Definition views.cppm:54
constexpr bool isNullable
Definition mapping.cppm:552
std::remove_reference_t< std::tuple_element_t< Index, typename detail::ReflectionTraits< detail::ReflectedType< T > >::Tuple > > field_type_t
FixedString(const char(&)[N]) -> FixedString< N - 1 >
constexpr std::size_t fieldCount
consteval auto fieldName() noexcept
constexpr auto typeNameStorage
constexpr bool is_relation_collection_v
consteval auto uuidStorages(Definitions...) -> model::UuidStorages< Definitions... >
Definition columns.cppm:716
consteval auto uuidStorage() -> model::UuidStorageDefinition< Member, Backend, Storage >
Definition columns.cppm:710
constexpr bool is_optional_relation_collection_v
model::Schema< Models... > Schema
Definition schema.cppm:504
A closed compile-time set of ORM models.
Definition schema.cppm:438
static constexpr auto storage
Definition columns.cppm:34
static constexpr auto member
Definition columns.cppm:32
static constexpr auto backend
Definition columns.cppm:33
consteval auto find(std::string_view name, db::BackendType backend) const -> UuidStorage
Definition columns.cppm:73
static consteval auto isValidFor() -> bool
Definition columns.cppm:46