ORM C++
Loading...
Searching...
No Matches
schema.cppm
Go to the documentation of this file.
1module;
2
3#include <array>
4#include <concepts>
5#include <cstddef>
6#include <span>
7#include <string_view>
8#include <type_traits>
9
10export module orm:model_schema;
11
12import orm.reflection;
13import :foundation;
14import :model_mapping;
15import :model_views;
16import :model_columns;
17import :model_relations;
18
19namespace orm::model
20{
21namespace detail
22{
23template <typename... Models>
24consteval auto hasUniqueTypes() -> bool
25{
26 constexpr std::array<TypeId, sizeof...(Models)> ids{typeId<Models>()...};
27 bool unique = true;
28 for (std::size_t left = 0; left < ids.size() && unique; ++left)
29 {
30 for (std::size_t right = left + 1; right < ids.size() && unique; ++right)
31 {
32 if (ids[left] == ids[right])
33 {
34 unique = false;
35 }
36 }
37 }
38 return unique;
39}
40}
41export
42{
43 // namespace detail
44
45 /**
46 * @brief Materializes one aggregate model's complete scalar metadata in static
47 * storage.
48 */
49 template <typename T, typename SchemaType>
50 struct StaticModel
51 {
52 static_assert(detail::StaticSchemaTraits<SchemaType>::template contains<T>,
53 "ORM_SCHEMA_MODEL_MISSING: a static descriptor requires its model to belong to Schema");
54 static_assert(std::is_aggregate_v<T>, "ORM_MODEL_AGGREGATE: an ORM model must be an aggregate");
55 static_assert(reflection::fieldCount<T> <= 128,
56 "ORM_MODEL_FIELD_LIMIT: automatic model reflection supports at most 128 fields");
57 static_assert(detail::hasValidTableNameDefinition<T>(),
58 "ORM_MODEL_TABLE_NAME: table_name must be a non-empty orm::reflection::FixedString");
59 static_assert(detail::hasValidColumnNamesDefinition<T>(),
60 "ORM_MODEL_COLUMN_MAPPING: columns_names must be a valid typed columnNames(...) definition");
61 static_assert(detail::hasValidStringLengthsDefinition<T>(),
62 "ORM_MODEL_STRING_LENGTH: string_lengths must uniquely map string members of this model");
63 static_assert(detail::hasValidUuidStorageDefinition<T>(),
64 "ORM_MODEL_UUID_STORAGE: uuid_storage must uniquely map UUID members per backend");
65 static_assert(
66 detail::hasValidPrimaryKeyDefinition<T>(),
67 "ORM_MODEL_PRIMARY_KEY_DEFINITION: id_columns must be a valid typed primaryKey<Members...>() definition");
68 static_assert(detail::hasValidAutoIncrementDefinition<T>(),
69 "ORM_MODEL_AUTO_INCREMENT_DEFINITION: auto_increment_columns must be a valid typed "
70 "autoIncrement<Members...>() definition");
71 static_assert(detail::hasValidRelationsDefinition<T>(),
72 "ORM_MODEL_RELATIONS_DEFINITION: relations must be a typed orm::relations(...) definition");
73 static_assert(detail::hasCompleteRelationDefinitions<T>(),
74 "ORM_RELATION_DESCRIPTOR_COUNT: every collection requires exactly one matching descriptor");
76 inline static constexpr auto columns = detail::staticColumns<T, SchemaType>;
77
78 static_assert(detail::hasValidColumnNames(columns),
79 "ORM_MODEL_COLUMN_NAME: model field and SQL column names must be non-empty and unique");
80 static_assert(detail::hasValidPrimaryKey(columns),
81 "ORM_MODEL_PRIMARY_KEY: primary-key members must be non-null scalar fields");
82 static_assert(detail::hasValidAutoIncrement(columns),
83 "ORM_MODEL_AUTO_INCREMENT: auto increment requires one "
84 "non-null int member which is the model's only primary key");
86 inline static constexpr auto primaryKeyIndices = detail::staticPrimaryKeyIndices<T, SchemaType>;
87 static_assert(
88 []
89 {
90 for (const auto index : primaryKeyIndices)
91 {
92 if (index >= columns.size())
93 {
94 return false;
95 }
96 }
97 return true;
98 }(),
99 "ORM_MODEL_PRIMARY_KEY_RELATION: primary keys must refer to scalar columns");
101 inline static constexpr auto relations = detail::makeRelations<T, SchemaType>();
103 inline static constexpr ModelDataView data{
104 .type = typeId<T>(),
105 .schemaIndex = detail::StaticSchemaTraits<SchemaType>::template indexOf<T>(),
106 .typeName = detail::modelTypeName<T>(),
107 .tableName = detail::mappedTableName<T>(),
108 .columns = columns,
109 .primaryKeyIndices = primaryKeyIndices,
110 .relations = relations,
111 };
112 };
113
114 template <typename SchemaType, typename T>
115 [[nodiscard]] consteval auto modelDescriptor() noexcept -> StaticModel<T, SchemaType>
116 {
117 return {};
118 }
119
120 template <typename SchemaType, typename T>
121 [[nodiscard]] constexpr auto modelView() noexcept -> ModelView
122 {
123 return ModelView{&SchemaType::view, detail::StaticSchemaTraits<SchemaType>::template indexOf<T>()};
124 }
125
126 template <typename T>
127 [[nodiscard]] consteval auto tableName() -> std::string_view
128 {
129 return detail::mappedTableName<T>();
130 }
131}
132} // namespace orm::model
133
134// model/Schema.hpp
135namespace orm::model
136{
137namespace detail
138{
139template <typename... Models>
140consteval auto hasUniqueTableNames() -> bool
141{
142 constexpr std::array<std::string_view, sizeof...(Models)> names{tableName<Models>()...};
143 for (std::size_t left = 0; left < names.size(); ++left)
144 {
145 for (std::size_t right = left + 1; right < names.size(); ++right)
146 {
147 if (names[left].compare(names[right]) == 0)
148 {
149 return false;
150 }
151 }
152 }
153 return true;
154}
155
156template <std::size_t Size>
157consteval auto hasValidRelationTargets(const std::array<const ModelDataView*, Size>& models) -> bool
158{
159 for (const auto* owner : models)
160 {
161 for (std::size_t relationIndex = 0; relationIndex < owner->relations.size(); ++relationIndex)
162 {
163 const auto& relation = owner->relations[relationIndex];
164 if (relation.targetModelIndex >= models.size())
165 {
166 return false;
167 }
168 const auto* target = models[relation.targetModelIndex];
169 if (target == nullptr || target->primaryKeyIndices.empty())
170 {
171 return false;
172 }
173
174 if (relation.kind == RelationKind::OneToMany)
175 {
176 if (relation.mappedBy.empty())
177 {
178 return false;
179 }
180 const auto* inverse = target->findRelationField(relation.mappedBy);
181 if (inverse == nullptr || inverse->kind != RelationKind::ToOne ||
182 inverse->targetModelIndex != owner->schemaIndex)
183 {
184 return false;
185 }
186 }
187 else if (relation.kind == RelationKind::ManyToMany && not relation.junction.isConfigured())
188 {
189 if (relation.mappedBy.empty())
190 {
191 return false;
192 }
193 const auto* owning = target->findRelationField(relation.mappedBy);
194 if (owning == nullptr || owning->kind != RelationKind::ManyToMany ||
195 owning->targetModelIndex != owner->schemaIndex || not owning->junction.isConfigured() ||
196 not owning->junction.owningSide)
197 {
198 return false;
199 }
200 }
201 }
202 }
203 return true;
204}
205
206[[nodiscard]] consteval auto foreignKeyColumnNameSize(std::string_view relationName,
207 std::string_view targetColumnName) -> std::size_t
208{
209 return relationName.size() + 1U + targetColumnName.size();
210}
211
212[[nodiscard]] consteval auto foreignKeyColumnNameCharacter(std::string_view relationName,
213 std::string_view targetColumnName, std::size_t index) -> char
214{
215 if (index < relationName.size())
216 {
217 return relationName[index];
218 }
219 if (index == relationName.size())
220 {
221 return '_';
222 }
223 return targetColumnName[index - relationName.size() - 1U];
224}
225
226[[nodiscard]] consteval auto equalsForeignKeyColumnName(std::string_view candidate, std::string_view relationName,
227 std::string_view targetColumnName) -> bool
228{
229 if (candidate.size() != foreignKeyColumnNameSize(relationName, targetColumnName))
230 {
231 return false;
232 }
233 for (std::size_t index = 0; index < candidate.size(); ++index)
234 {
235 if (candidate[index] != foreignKeyColumnNameCharacter(relationName, targetColumnName, index))
236 {
237 return false;
238 }
239 }
240 return true;
241}
242
243[[nodiscard]] consteval auto equalForeignKeyColumnNames(std::string_view leftRelation,
244 std::string_view leftTargetColumn,
245 std::string_view rightRelation,
246 std::string_view rightTargetColumn) -> bool
247{
248 const auto size = foreignKeyColumnNameSize(leftRelation, leftTargetColumn);
249 if (size != foreignKeyColumnNameSize(rightRelation, rightTargetColumn))
250 {
251 return false;
252 }
253 for (std::size_t index = 0; index < size; ++index)
254 {
255 if (foreignKeyColumnNameCharacter(leftRelation, leftTargetColumn, index) !=
256 foreignKeyColumnNameCharacter(rightRelation, rightTargetColumn, index))
257 {
258 return false;
259 }
260 }
261 return true;
262}
263
264template <std::size_t Size>
265consteval auto hasUniquePhysicalColumnNames(const std::array<const ModelDataView*, Size>& models) -> bool
266{
267 for (const auto* owner : models)
268 {
269 for (std::size_t scalarIndex = 0; scalarIndex < owner->columns.size(); ++scalarIndex)
270 {
271 const auto& scalar = owner->columns[scalarIndex];
272 if (scalar.kind != FieldKind::Scalar)
273 {
274 continue;
275 }
276 for (std::size_t relationColumnIndex = 0; relationColumnIndex < owner->columns.size();
277 ++relationColumnIndex)
278 {
279 const auto& relation = owner->columns[relationColumnIndex];
280 if (relation.kind != FieldKind::ToOne || relation.targetModelIndex >= models.size())
281 {
282 continue;
283 }
284 const auto* target = models[relation.targetModelIndex];
285 for (std::size_t keyIndex = 0; keyIndex < target->primaryKeyIndices.size(); ++keyIndex)
286 {
287 const auto primaryKeyIndex = target->primaryKeyIndices[keyIndex];
288 if (primaryKeyIndex >= target->columns.size() ||
289 equalsForeignKeyColumnName(scalar.name, relation.name, target->columns[primaryKeyIndex].name))
290 {
291 return false;
292 }
293 }
294 }
295 }
296
297 for (std::size_t leftRelationIndex = 0; leftRelationIndex < owner->columns.size(); ++leftRelationIndex)
298 {
299 const auto& leftRelation = owner->columns[leftRelationIndex];
300 if (leftRelation.kind != FieldKind::ToOne || leftRelation.targetModelIndex >= models.size())
301 {
302 continue;
303 }
304 const auto* leftTarget = models[leftRelation.targetModelIndex];
305 for (std::size_t leftKeyIndex = 0; leftKeyIndex < leftTarget->primaryKeyIndices.size(); ++leftKeyIndex)
306 {
307 const auto leftPrimaryKeyIndex = leftTarget->primaryKeyIndices[leftKeyIndex];
308 if (leftPrimaryKeyIndex >= leftTarget->columns.size())
309 {
310 return false;
311 }
312 for (std::size_t rightRelationIndex = leftRelationIndex + 1; rightRelationIndex < owner->columns.size();
313 ++rightRelationIndex)
314 {
315 const auto& rightRelation = owner->columns[rightRelationIndex];
316 if (rightRelation.kind != FieldKind::ToOne || rightRelation.targetModelIndex >= models.size())
317 {
318 continue;
319 }
320 const auto* rightTarget = models[rightRelation.targetModelIndex];
321 for (std::size_t rightKeyIndex = 0; rightKeyIndex < rightTarget->primaryKeyIndices.size();
322 ++rightKeyIndex)
323 {
324 const auto rightPrimaryKeyIndex = rightTarget->primaryKeyIndices[rightKeyIndex];
325 if (rightPrimaryKeyIndex >= rightTarget->columns.size() ||
326 equalForeignKeyColumnNames(leftRelation.name, leftTarget->columns[leftPrimaryKeyIndex].name,
327 rightRelation.name,
328 rightTarget->columns[rightPrimaryKeyIndex].name))
329 {
330 return false;
331 }
332 }
333 }
334 }
335 }
336 }
337 return true;
338}
339
340[[nodiscard]] consteval auto hasUniqueNames(std::span<const std::string_view> left,
341 std::span<const std::string_view> right = {}) -> bool
342{
343 for (std::size_t leftIndex = 0; leftIndex < left.size(); ++leftIndex)
344 {
345 if (left[leftIndex].empty())
346 {
347 return false;
348 }
349 for (std::size_t other = leftIndex + 1; other < left.size(); ++other)
350 {
351 if (left[leftIndex].compare(left[other]) == 0)
352 {
353 return false;
354 }
355 }
356 for (std::size_t rightIndex = 0; rightIndex < right.size(); ++rightIndex)
357 {
358 const auto rightName = right[rightIndex];
359 if (rightName.empty() || left[leftIndex].compare(rightName) == 0)
360 {
361 return false;
362 }
363 }
364 }
365 for (std::size_t rightIndex = 0; rightIndex < right.size(); ++rightIndex)
366 {
367 if (right[rightIndex].empty())
368 {
369 return false;
370 }
371 for (std::size_t other = rightIndex + 1; other < right.size(); ++other)
372 {
373 if (right[rightIndex].compare(right[other]) == 0)
374 {
375 return false;
376 }
377 }
378 }
379 return true;
380}
381
382template <std::size_t Size>
383consteval auto hasValidJunctions(const std::array<const ModelDataView*, Size>& models) -> bool
384{
385 for (std::size_t ownerIndex = 0; ownerIndex < models.size(); ++ownerIndex)
386 {
387 const auto* owner = models[ownerIndex];
388 for (std::size_t relationIndex = 0; relationIndex < owner->relations.size(); ++relationIndex)
389 {
390 const auto& relation = owner->relations[relationIndex];
391 if (relation.kind != RelationKind::ManyToMany || not relation.junction.isConfigured())
392 {
393 continue;
394 }
395 const auto* target = models[relation.targetModelIndex];
396 if (not relation.mappedBy.empty() || not relation.junction.owningSide ||
397 relation.junction.ownerColumns.size() != owner->primaryKeyIndices.size() ||
398 relation.junction.targetColumns.size() != target->primaryKeyIndices.size() ||
399 not hasUniqueNames(relation.junction.ownerColumns, relation.junction.targetColumns))
400 {
401 return false;
402 }
403 for (const auto* model : models)
404 {
405 if (model->tableName.compare(relation.junction.tableName) == 0)
406 {
407 return false;
408 }
409 }
410 for (std::size_t otherOwnerIndex = ownerIndex; otherOwnerIndex < models.size(); ++otherOwnerIndex)
411 {
412 const auto* otherOwner = models[otherOwnerIndex];
413 const auto firstRelation = otherOwnerIndex == ownerIndex ? relationIndex + 1 : std::size_t{};
414 for (std::size_t otherRelationIndex = firstRelation; otherRelationIndex < otherOwner->relations.size();
415 ++otherRelationIndex)
416 {
417 const auto& other = otherOwner->relations[otherRelationIndex];
418 if (other.kind == RelationKind::ManyToMany && other.junction.isConfigured() &&
419 other.junction.tableName.compare(relation.junction.tableName) == 0)
420 {
421 return false;
422 }
423 }
424 }
425 }
426 }
427 return true;
428}
429}
430export
431{
432 // namespace detail
433
434 /**
435 * @brief A closed compile-time set of ORM models.
436 */
437 template <typename... Models>
438 struct Schema
439 {
440 static_assert(detail::hasUniqueTypes<Models...>(),
441 "ORM_SCHEMA_DUPLICATE_MODEL: a schema may list a model type only once");
442 static_assert(detail::hasUniqueTableNames<Models...>(),
443 "ORM_SCHEMA_DUPLICATE_TABLE: every model in a schema must use a unique table name");
444
445 template <typename Model>
446 inline static constexpr bool contains = (std::same_as<Model, Models> || ...);
447
448 template <typename Model>
449 [[nodiscard]] static consteval auto indexOf() -> std::size_t
450 {
451 static_assert(contains<Model>,
452 "ORM_SCHEMA_MODEL_MISSING: requested model type does not belong to this schema");
453 constexpr std::array<bool, sizeof...(Models)> matches{std::same_as<Model, Models>...};
454 for (std::size_t index = 0; index < matches.size(); ++index)
455 {
456 if (matches[index])
457 {
458 return index;
459 }
460 }
461 return 0;
462 }
464 [[nodiscard]] static constexpr auto modelAt(std::size_t index) noexcept -> ModelView
465 {
466 return view.at(index);
467 }
469 inline static constexpr std::array<const ModelDataView*, sizeof...(Models)> modelStorage{
470 &StaticModel<Models, Schema<Models...>>::data...};
471
472 static_assert(detail::hasUniquePhysicalColumnNames(modelStorage),
473 "ORM_SCHEMA_COLUMN_COLLISION: scalar and generated foreign-key column names must be unique");
474
475 static_assert(detail::hasValidRelationTargets(modelStorage),
476 "ORM_SCHEMA_RELATION_GRAPH: mappedBy must resolve to a compatible relation in the closed schema");
477 static_assert(
478 detail::hasValidJunctions(modelStorage),
479 "ORM_SCHEMA_JUNCTION: junction tables and columns must be unique and match endpoint primary keys");
481 inline static constexpr SchemaView view{.models = modelStorage};
482 };
483
484 template <typename SchemaType>
485 [[nodiscard]] constexpr auto schemaView() noexcept -> const SchemaView&
486 {
487 return SchemaType::view;
488 }
489
490 template <typename SchemaType, typename T>
491 consteval auto requireSchemaModel() -> void
492 {
493 static_assert(SchemaType::template contains<std::remove_cv_t<T>>,
494 "ORM_SCHEMA_MODEL_MISSING: requested model type does not belong to the closed schema");
495 }
496}
497} // namespace orm::model
498
499namespace orm
500{
501export
502{
503
504 template <typename... Models>
505 using Schema = model::Schema<Models...>;
506
507 template <typename SchemaType, typename T>
508 [[nodiscard]] consteval auto modelDescriptor() noexcept -> model::StaticModel<T, SchemaType>
509 {
511 }
512
513 template <typename SchemaType, typename T>
514 [[nodiscard]] constexpr auto modelView() noexcept -> model::ModelView
515 {
517 }
518}
519} // namespace orm
auto compare(const SchemaSnapshot &before, const SchemaSnapshot &after, const GenerationDecisions &decisions={}) -> SchemaDiff
constexpr auto schemaView() noexcept -> const SchemaView &
Definition schema.cppm:484
consteval auto requireSchemaModel() -> void
Definition schema.cppm:490
consteval auto modelDescriptor() noexcept -> StaticModel< T, SchemaType >
Definition schema.cppm:114
consteval auto tableName() -> std::string_view
Definition schema.cppm:126
consteval auto typeId() noexcept -> TypeId
Definition views.cppm:35
constexpr auto modelView() noexcept -> ModelView
Definition schema.cppm:120
constexpr std::size_t fieldCount
constexpr auto modelView() noexcept -> model::ModelView
Definition schema.cppm:513
consteval auto modelDescriptor() noexcept -> model::StaticModel< T, SchemaType >
Definition schema.cppm:507
model::Schema< Models... > Schema
Definition schema.cppm:504
Immutable data stored once for a model inside a closed schema.
Definition views.cppm:118
Trivially-copyable handle to one model in immutable Schema storage.
Definition views.cppm:181
Immutable view over a statically materialized schema.
Definition views.cppm:208
constexpr auto at(std::size_t index) const noexcept -> ModelView
Definition views.cppm:211
A closed compile-time set of ORM models.
Definition schema.cppm:438
static constexpr std::array< const ModelDataView *, sizeof...(Models)> modelStorage
Definition schema.cppm:468
static constexpr SchemaView view
Definition schema.cppm:480
static constexpr auto modelAt(std::size_t index) noexcept -> ModelView
Definition schema.cppm:463
static consteval auto indexOf() -> std::size_t
Definition schema.cppm:448
static constexpr bool contains
Definition schema.cppm:445
Materializes one aggregate model's complete scalar metadata in static storage.
Definition schema.cppm:50
static constexpr auto primaryKeyIndices
Definition schema.cppm:85
static constexpr auto relations
Definition schema.cppm:100
static constexpr auto columns
Definition schema.cppm:75
static constexpr ModelDataView data
Definition schema.cppm:102