ORM C++
Loading...
Searching...
No Matches
relations.cppm
Go to the documentation of this file.
1module;
2
3#include <array>
4#include <concepts>
5#include <cstddef>
6#include <string_view>
7#include <tuple>
8#include <type_traits>
9#include <utility>
10
11export module orm:model_relations;
12
13import orm.reflection;
14import :foundation;
15import :model_mapping;
16import :model_views;
17import :model_columns;
18
19namespace orm::model::detail
20{
21template <typename Model>
22consteval auto relationDefinitions()
23{
24 if constexpr (requires { Model::relations; })
25 {
26 using definition_t = std::remove_cvref_t<decltype(Model::relations)>;
27 if constexpr (IsRelations<definition_t>::value)
28 {
29 return Model::relations;
30 }
31 else
32 {
33 return std::tuple{};
34 }
35 }
36 else
37 {
38 return std::tuple{};
39 }
40}
41
42template <typename Model>
43using relation_definitions_t = std::remove_cvref_t<decltype(relationDefinitions<Model>())>;
44
45template <typename Model>
46consteval auto hasValidRelationsDefinition() -> bool
47{
48 if constexpr (requires { Model::relations; })
49 {
50 using definition_t = std::remove_cvref_t<decltype(Model::relations)>;
51 return IsRelations<definition_t>::value;
52 }
53 return true;
54}
55
56template <typename Descriptor>
57consteval auto relationFieldName() -> std::string_view
58{
59 return reflectedMemberNameStorage<Descriptor::member>.view();
60}
61
62template <typename Descriptor>
63consteval auto relationMappedByName() -> std::string_view
64{
65 if constexpr (std::is_same_v<std::remove_cv_t<decltype(Descriptor::mappedByMember)>, std::nullptr_t>)
66 {
67 return Descriptor::mappedByName.view();
68 }
69 else
70 {
71 return reflectedMemberNameStorage<Descriptor::mappedByMember>.view();
72 }
73}
74
75template <typename Descriptor>
76using relation_field_t = std::remove_cvref_t<orm::detail::relation_member_value_t<Descriptor::member>>;
77
78template <typename Descriptor>
80
81template <typename Model, typename Descriptor>
82consteval auto isValidRelationDescriptor() -> bool
83{
84 if constexpr (not orm::detail::IsRelationDescriptor<Descriptor>::value)
85 {
86 return false;
87 }
88 else if constexpr (not std::same_as<orm::detail::relation_member_owner_t<Descriptor::member>, Model>)
89 {
90 return false;
91 }
92 else if constexpr (not memberExists<Model, Descriptor::member>())
93 {
94 return false;
95 }
96 else if constexpr (orm::detail::IsOneToManyDescriptor<Descriptor>::value)
97 {
99 }
100 else
101 {
104 }
105}
106
107template <typename Model, typename... Descriptors>
108consteval auto hasUniqueValidRelationDescriptors(std::tuple<Descriptors...>) -> bool
109{
110 if constexpr (not(isValidRelationDescriptor<Model, Descriptors>() && ...))
111 {
112 return false;
113 }
114 else
115 {
116 constexpr std::array<std::string_view, sizeof...(Descriptors)> names{relationFieldName<Descriptors>()...};
117 bool unique = true;
118 for (std::size_t left = 0; left < names.size() && unique; ++left)
119 {
120 for (std::size_t right = left + 1; right < names.size() && unique; ++right)
121 {
122 if (names[left].compare(names[right]) == 0)
123 {
124 unique = false;
125 }
126 }
127 }
128 return unique;
129 }
130}
131
132template <typename Model, std::size_t... Indices>
133consteval auto collectionFieldCount(std::index_sequence<Indices...>) -> std::size_t
134{
136}
137
138template <typename Model>
139consteval auto hasCompleteRelationDefinitions() -> bool
140{
141 constexpr auto definitions = relationDefinitions<Model>();
142 return hasValidRelationsDefinition<Model>() && hasUniqueValidRelationDescriptors<Model>(definitions) &&
143 std::tuple_size_v<relation_definitions_t<Model>> ==
144 collectionFieldCount<Model>(std::make_index_sequence<reflection::fieldCount<Model>>{});
145}
146
147template <typename Model>
148consteval auto validatedRelationDefinitions()
149{
150 if constexpr (hasCompleteRelationDefinitions<Model>())
151 {
152 return relationDefinitions<Model>();
153 }
154 else
155 {
156 return std::tuple{};
157 }
158}
159
160template <std::size_t Capacity>
161struct RelationNameBuffer
162{
163 std::array<char, Capacity> data{};
164 std::size_t size{};
165
166 [[nodiscard]] constexpr auto view() const noexcept -> std::string_view
167 {
168 return {data.data(), size};
169 }
170};
171
172template <typename Model, typename SchemaType>
173struct DefaultJunctionColumnStorage
174{
175 inline static constexpr auto& columns = staticColumns<Model, SchemaType>;
176 inline static constexpr auto& primaryKeyIndices = staticPrimaryKeyIndices<Model, SchemaType>;
177 inline static constexpr auto capacity = []
178 {
179 std::size_t result = mappedTableName<Model>().size() + 2;
180 for (const auto columnIndex : primaryKeyIndices)
181 {
182 result = result < mappedTableName<Model>().size() + 1 + columns[columnIndex].name.size() + 1 ?
183 mappedTableName<Model>().size() + 1 + columns[columnIndex].name.size() + 1 :
184 result;
185 }
186 return result;
187 }();
188
189 inline static constexpr auto buffers = []
190 {
191 std::array<RelationNameBuffer<capacity>, primaryKeyIndices.size()> result{};
192 for (std::size_t keyIndex = 0; keyIndex < primaryKeyIndices.size(); ++keyIndex)
193 {
194 auto& output = result[keyIndex];
195 const auto table = mappedTableName<Model>();
196 const auto column = columns[primaryKeyIndices[keyIndex]].name;
197 for (const auto character : table)
198 {
199 output.data[output.size++] = character;
200 }
201 output.data[output.size++] = '_';
202 for (const auto character : column)
203 {
204 output.data[output.size++] = character;
205 }
206 }
207 return result;
208 }();
209
210 inline static constexpr auto names = []
211 {
212 std::array<std::string_view, primaryKeyIndices.size()> result{};
213 for (std::size_t index = 0; index < result.size(); ++index)
214 {
215 result[index] = buffers[index].view();
216 }
217 return result;
218 }();
219};
220
221template <typename Descriptor, typename Owner, typename Target, typename SchemaType>
222struct JunctionStorage
223{
224 inline static constexpr auto& defaultOwner = DefaultJunctionColumnStorage<Owner, SchemaType>::names;
225 inline static constexpr auto& defaultTarget = DefaultJunctionColumnStorage<Target, SchemaType>::names;
226 inline static constexpr auto& owner = []() -> const auto&
227 {
228 if constexpr (Descriptor::OwnerColumns::size == 0)
229 {
230 return defaultOwner;
231 }
232 else
233 {
234 return Descriptor::OwnerColumns::values;
235 }
236 }();
237 inline static constexpr auto& target = []() -> const auto&
238 {
239 if constexpr (Descriptor::TargetColumns::size == 0)
240 {
241 return defaultTarget;
242 }
243 else
244 {
245 return Descriptor::TargetColumns::values;
246 }
247 }();
248};
249
250template <typename Model, typename SchemaType, std::size_t Index>
251consteval auto isToOneField() -> bool
252{
254 using value_t = std::remove_cv_t<static_optional_value_t<std::remove_cvref_t<field_t>>>;
255 return not is_relation_collection_v<field_t> && StaticSchemaTraits<SchemaType>::template contains<value_t>;
256}
257
258template <typename Model, typename SchemaType, std::size_t... Indices>
259consteval auto makeToOneRelations(std::index_sequence<Indices...>)
260{
261 constexpr auto count = ((isToOneField<Model, SchemaType, Indices>() ? 1U : 0U) + ... + 0U);
262 std::array<RelationView, count> result{};
263 std::size_t output{};
264 (
265 [&]
266 {
267 if constexpr (isToOneField<Model, SchemaType, Indices>())
268 {
270 using target_t = std::remove_cv_t<static_optional_value_t<std::remove_cvref_t<field_t>>>;
271 constexpr auto fieldName = reflectedFieldName<Model, Indices>();
272 result[output++] = RelationView{
273 .fieldIndex = Indices,
274 .fieldName = fieldName,
275 .columnName = mappedColumnName<Model>(fieldName),
276 .kind = RelationKind::ToOne,
277 .mappedBy = {},
278 .nullable = isNullable<field_t>,
279 .targetModelIndex = StaticSchemaTraits<SchemaType>::template indexOf<target_t>(),
280 .junction = {},
281 };
282 }
283 }(),
284 ...);
285 return result;
286}
287
288template <typename Model, typename SchemaType, typename Descriptor>
289consteval auto makeCollectionRelation() -> RelationView
290{
291 using target_t = relation_target_t<Descriptor>;
292 if constexpr (not StaticSchemaTraits<SchemaType>::template contains<target_t>)
293 {
294 static_assert(StaticSchemaTraits<SchemaType>::template contains<target_t>,
295 "ORM_RELATION_TARGET_MISSING: collection target must belong to Schema");
296 return {};
297 }
298 else
299 {
300 static_assert(hasPrimaryKey<Model>() && hasPrimaryKey<target_t>(),
301 "ORM_RELATION_KEYLESS: collection endpoints must define primary keys");
302
303 constexpr auto fieldName = relationFieldName<Descriptor>();
304 constexpr auto mappedBy = relationMappedByName<Descriptor>();
305 RelationView result{
306 .fieldIndex = memberIndex<Model, Descriptor::member>(),
307 .fieldName = fieldName,
308 .columnName = fieldName,
309 .kind = orm::detail::IsOneToManyDescriptor<Descriptor>::value ? RelationKind::OneToMany :
311 .mappedBy = mappedBy,
312 .nullable = false,
313 .targetModelIndex = StaticSchemaTraits<SchemaType>::template indexOf<target_t>(),
314 .junction = {},
315 };
316
317 if constexpr (orm::detail::IsOneToManyDescriptor<Descriptor>::value)
318 {
319 static_assert(not mappedBy.empty(), "ORM_RELATION_ONE_TO_MANY_MAPPED_BY: one-to-many requires mappedBy");
320 }
321 else
322 {
323 constexpr auto isInverse = not mappedBy.empty();
324 if constexpr (isInverse)
325 {
326 static_assert(Descriptor::throughTable.view().empty() && Descriptor::OwnerColumns::size == 0 &&
327 Descriptor::TargetColumns::size == 0,
328 "ORM_RELATION_INVERSE_CONFIG: inverse many-to-many may only use mappedBy");
329 }
330 else
331 {
332 static_assert(not Descriptor::throughTable.view().empty(),
333 "ORM_RELATION_JUNCTION_MISSING: owning many-to-many requires through");
334 using storage_t = JunctionStorage<Descriptor, Model, target_t, SchemaType>;
335 static_assert(storage_t::owner.size() == staticPrimaryKeyIndices<Model, SchemaType>.size(),
336 "ORM_RELATION_OWNER_COLUMN_COUNT: owner junction columns must match owner PK");
337 static_assert(storage_t::target.size() == staticPrimaryKeyIndices<target_t, SchemaType>.size(),
338 "ORM_RELATION_TARGET_COLUMN_COUNT: target junction columns must match target PK");
339 result.junction = JunctionView{
340 .tableName = Descriptor::throughTable.view(),
341 .ownerColumns = storage_t::owner,
342 .targetColumns = storage_t::target,
343 .owningSide = true,
344 };
345 }
346 }
347 return result;
348 }
349}
350
351template <typename Model, typename SchemaType, typename... Descriptors>
352consteval auto makeCollectionRelations(std::tuple<Descriptors...>)
353{
354 return std::array<RelationView, sizeof...(Descriptors)>{
355 makeCollectionRelation<Model, SchemaType, Descriptors>()...};
356}
357
358template <typename Model, typename SchemaType>
359consteval auto makeRelations()
360{
361 constexpr auto toOne =
362 makeToOneRelations<Model, SchemaType>(std::make_index_sequence<reflection::fieldCount<Model>>{});
363 constexpr auto collections = makeCollectionRelations<Model, SchemaType>(validatedRelationDefinitions<Model>());
364 std::array<RelationView, toOne.size() + collections.size()> result{};
365 std::size_t output{};
366 for (const auto& relation : toOne)
367 {
368 result[output++] = relation;
369 }
370 for (const auto& relation : collections)
371 {
372 result[output++] = relation;
373 }
374 return result;
375}
376} // namespace orm::model::detail
auto compare(const SchemaSnapshot &before, const SchemaSnapshot &after, const GenerationDecisions &decisions={}) -> SchemaDiff
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
constexpr std::size_t fieldCount
consteval auto fieldName() noexcept
typename detail::RelationCollectionTraits< std::remove_cvref_t< T > >::Target relation_target_t
constexpr bool is_one_to_many_v
constexpr bool is_relation_collection_v