ORM C++
Loading...
Searching...
No Matches
object_binding.cppm
Go to the documentation of this file.
1module;
2
3#include <cstddef>
4#include <format>
5#include <optional>
6#include <sstream>
7#include <stdexcept>
8#include <string>
9#include <string_view>
10#include <tuple>
11#include <type_traits>
12#include <utility>
13
14export module orm:database_object_binding;
15
16import orm.reflection;
17import :foundation;
18import :model;
19export import :database_payload;
20
21namespace orm::db::binding
22{
23template <typename ModelField>
24auto getScalarFieldValue(const auto& values, const std::string& fieldName) -> ModelField
25{
27 {
28 if (values.get_indicator(fieldName) == soci::i_null)
29 {
31 }
32
33 using value_type = typename NullableAdapter<ModelField>::Value;
35 }
36 else if constexpr (ValueConvertible<ModelField>)
37 {
38 using canonical_type = typename ValueConverter<ModelField>::Value;
39 canonical_type canonical;
41 canonical = getEncodedScalarValue<canonical_type>(values, fieldName);
42 else if constexpr (std::is_arithmetic_v<canonical_type>)
43 canonical = getNumericValue<canonical_type>(values, fieldName);
44 else if constexpr (SociDefaultSupported<canonical_type>)
45 canonical = values.template get<canonical_type>(fieldName);
46 else
47 throw ConversionError{"Unsupported value converter canonical type: " + fieldName};
48
49 try
50 {
52 }
53 catch (const std::invalid_argument&)
54 {
55 throw ConversionError{"A database value was rejected by its converter"};
56 }
57 }
58 else if constexpr (SociEncodedValue<ModelField>)
59 {
60 return getEncodedScalarValue<ModelField>(values, fieldName);
61 }
62 else if constexpr (std::is_arithmetic_v<ModelField>)
63 {
64 return getNumericValue<ModelField>(values, fieldName);
65 }
66 else if constexpr (SociDefaultSupported<ModelField>)
67 {
68 return values.template get<ModelField>(fieldName);
69 }
70 else
71 {
72 throw ConversionError{"Unsupported related model field type: " + fieldName};
73 }
74}
75
76namespace detail
77{
78template <typename Owner>
79[[nodiscard]] auto selectedScalarAlias(const model::ModelView& owner, const model::ColumnView& column) -> std::string
80{
81 return std::format("{}_{}", owner->tableName, column.name);
82}
83
84template <bool JoinedValues>
85[[nodiscard]] auto selectedRelatedAlias(const model::ModelView& owner, const model::ColumnView& relationColumn,
86 const model::ColumnView& targetColumn) -> std::string
87{
88 if constexpr (JoinedValues)
89 {
90 return std::format("{}_{}", relationColumn.name, targetColumn.name);
91 }
92 else
93 {
94 return std::format("{}_{}_{}", owner->tableName, relationColumn.name, targetColumn.name);
95 }
96}
97
98template <typename Related, typename SchemaType, bool JoinedValues>
99auto hydrateRelated(Related& related, const model::ModelView& owner, const model::ColumnView& relationColumn,
100 const auto& values) -> void
101{
102 using related_t = std::remove_cv_t<Related>;
103 auto relatedFields = reflection::fieldPointers(related);
104
105 auto hydrate = [&]<typename Index>(Index, auto* field)
106 {
107 using field_t = std::decay_t<decltype(*field)>;
109 {
110 return;
111 }
112 else
113 {
114 constexpr auto* targetColumn = mappedColumn<related_t, SchemaType, Index::value>;
115 if constexpr (targetColumn != nullptr)
116 {
117 if constexpr (JoinedValues)
118 {
119 const auto alias = selectedRelatedAlias<true>(owner, relationColumn, *targetColumn);
120 *field = getScalarFieldValue<field_t>(values, alias);
121 }
122 else if (targetColumn->isPrimaryKey)
123 {
124 const auto alias = selectedRelatedAlias<false>(owner, relationColumn, *targetColumn);
125 *field = getScalarFieldValue<field_t>(values, alias);
126 }
127 }
128 }
129 };
130
131 utils::constexpr_for_tuple(relatedFields, hydrate);
132}
133
134template <typename Related, typename SchemaType, bool JoinedValues>
135[[nodiscard]] auto relatedPrimaryKeyIsPresent(const model::ModelView& owner, const model::ColumnView& relationColumn,
136 const auto& values) -> bool
137{
138 constexpr auto related = model::modelView<SchemaType, Related>();
139 bool hasPresentPrimaryKey{};
140 bool hasNullPrimaryKey{};
141
142 for (const auto primaryKeyIndex : related->primaryKeyIndices)
143 {
144 const auto& targetColumn = related->columns[primaryKeyIndex];
145 const auto alias = selectedRelatedAlias<JoinedValues>(owner, relationColumn, targetColumn);
146 if (values.get_indicator(alias) == soci::i_null)
147 {
148 hasNullPrimaryKey = true;
149 }
150 else
151 {
152 hasPresentPrimaryKey = true;
153 }
154 }
155
156 if (not hasPresentPrimaryKey)
157 {
158 return false;
159 }
160 if (hasNullPrimaryKey)
161 {
162 throw ConversionError{"Cannot hydrate optional relation with a partially null primary key"};
163 }
164 return true;
165}
166} // namespace detail
167
168template <typename ModelField>
170{
171 template <typename T, typename SchemaType, bool JoinedValues>
172 static auto get(ModelField* field, const BindingPayload<T, SchemaType, JoinedValues>&,
173 const model::ColumnView& column, const auto& values) -> void
174 {
175 constexpr auto owner = model::modelView<SchemaType, T>();
176
178 {
179 using related_t = std::remove_cv_t<optional_value_t<ModelField>>;
180
181 if constexpr (model::isNullable<ModelField>)
182 {
183 if (not detail::relatedPrimaryKeyIsPresent<related_t, SchemaType, JoinedValues>(owner, column, values))
184 {
186 return;
187 }
188 related_t related{};
189 detail::hydrateRelated<related_t, SchemaType, JoinedValues>(related, owner, column, values);
190 *field = makeNullableValue<ModelField>(std::move(related));
191 }
192 else
193 {
194 detail::hydrateRelated<ModelField, SchemaType, JoinedValues>(*field, owner, column, values);
195 }
196 }
197 else
198 {
199 const auto alias = detail::selectedScalarAlias<T>(owner, column);
200 *field = getScalarFieldValue<ModelField>(values, alias);
201 }
202 }
203
204 template <typename T, typename SchemaType, bool JoinedValues, std::size_t FieldIndex>
205 static auto get(ModelField* field, const BindingPayload<T, SchemaType, JoinedValues>& payload,
206 std::integral_constant<std::size_t, FieldIndex>, const auto& values) -> void
207 {
208 get(field, payload, payload.template columnDescriptor<FieldIndex>(), values);
209 }
210
211 template <typename T, typename SchemaType, bool JoinedValues>
212 static auto get(ModelField* field, const BindingPayload<T, SchemaType, JoinedValues>& payload,
213 std::size_t fieldIndex, const auto& values) -> void
214 {
215 get(field, payload, payload.columnDescriptor(fieldIndex), values);
216 }
217};
218} // namespace orm::db::binding
219namespace orm::db::binding
220{
221template <typename T>
222inline auto bindTypedNull(soci::values& values, std::string_view name, const T& value) -> void
223{
224 const auto parameterName = std::string{name};
225
226 // SOCI's initial values::set() conversion resets the indicator to i_ok.
227 // Set the indicator only after the named value and its storage type exist.
228 values.set(parameterName, value);
229 values.set(parameterName, value, soci::i_null);
230}
231} // namespace orm::db::binding
232namespace orm::db::binding
233{
234inline auto setNullValue(soci::values& values, const std::string& name, model::ColumnType type) -> void
235{
236 switch (type)
237 {
244 bindTypedNull(values, name, int{});
245 return;
248 bindTypedNull(values, name, static_cast<unsigned long long>(0));
249 return;
251 bindTypedNull(values, name, static_cast<long long>(0));
252 return;
255 bindTypedNull(values, name, 0.0);
256 return;
258 bindTypedNull(values, name, std::string{});
259 return;
265 bindTypedNull(values, name, std::string{});
266 return;
267 }
268
269 throw std::invalid_argument{"Cannot bind NULL value with unsupported column type"};
270}
271
272inline auto validateStringLength(std::string_view text, std::optional<std::size_t> limit) -> void
273{
274 if (!limit)
275 return;
276 std::size_t characters{};
277 for (std::size_t offset = 0; offset < text.size();)
278 {
279 const auto first = static_cast<unsigned char>(text[offset++]);
280 std::size_t remaining{};
281 unsigned long codePoint{};
282 unsigned long minimum{};
283 if (first < 0x80)
284 codePoint = first;
285 else if (first >= 0xc2 && first <= 0xdf)
286 {
287 remaining = 1;
288 codePoint = first & 0x1f;
289 minimum = 0x80;
290 }
291 else if (first >= 0xe0 && first <= 0xef)
292 {
293 remaining = 2;
294 codePoint = first & 0x0f;
295 minimum = 0x800;
296 }
297 else if (first >= 0xf0 && first <= 0xf4)
298 {
299 remaining = 3;
300 codePoint = first & 0x07;
301 minimum = 0x10000;
302 }
303 else
304 throw ConversionError{"A bounded string must contain valid UTF-8"};
305 if (remaining > text.size() - offset)
306 throw ConversionError{"A bounded string must contain valid UTF-8"};
307 while (remaining > 0)
308 {
309 --remaining;
310 const auto continuation = static_cast<unsigned char>(text[offset++]);
311 if ((continuation & 0xc0) != 0x80)
312 throw ConversionError{"A bounded string must contain valid UTF-8"};
313 codePoint = (codePoint << 6) | (continuation & 0x3f);
314 }
315 if (codePoint < minimum || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff))
316 throw ConversionError{"A bounded string must contain valid UTF-8"};
317 if (++characters > *limit)
318 throw ConversionError{"A string exceeds its declared character limit"};
319 }
320}
321
322template <typename ModelField>
323auto setScalarFieldValue(soci::values& values, const std::string& fieldName, const ModelField& field,
324 model::ColumnType columnType,
325 std::optional<std::size_t> maxStringLength = std::nullopt) -> void
326{
327 if constexpr (model::isNullable<ModelField>)
328 {
330 {
331 setNullValue(values, fieldName, columnType);
332 return;
333 }
334
335 setScalarFieldValue(values, fieldName, NullableAdapter<ModelField>::value(field), columnType, maxStringLength);
336 }
337 else if constexpr (ValueConvertible<ModelField>)
338 {
339 try
340 {
341 const auto canonical = ValueConverter<ModelField>::toValue(field);
342 setScalarFieldValue(values, fieldName, canonical, columnType, maxStringLength);
343 }
344 catch (const std::invalid_argument&)
345 {
346 throw ConversionError{"A value was rejected by its converter"};
347 }
348 }
349 else if constexpr (SociEncodedValue<ModelField>)
350 {
351 values.set(fieldName, encodeScalarValue(field));
352 }
353 else if constexpr (SociConvertableToDouble<ModelField>)
354 {
355 values.set(fieldName, checkedNumericCast<double>(field, fieldName));
356 }
357 else if constexpr (SociConvertableToInt<ModelField>)
358 {
359 values.set(fieldName, checkedNumericCast<int>(field, fieldName));
360 }
361 else if constexpr (SociConvertableToLongLong<ModelField>)
362 {
363 values.set(fieldName, checkedNumericCast<long long>(field, fieldName));
364 }
366 {
367 values.set(fieldName, checkedNumericCast<unsigned long long>(field, fieldName));
368 }
369 else if constexpr (SociDefaultSupported<ModelField>)
370 {
371 if constexpr (std::is_arithmetic_v<ModelField>)
372 {
373 values.set(fieldName, checkedNumericCast<ModelField>(field, fieldName));
374 }
375 else
376 {
377 if constexpr (std::same_as<ModelField, std::string>)
378 validateStringLength(field, maxStringLength);
379 values.set(fieldName, field);
380 }
381 }
382 else
383 {
384 throw std::invalid_argument{"Unsupported related model field type: " + fieldName};
385 }
386}
387
388namespace detail
389{
390template <typename Related, typename SchemaType>
391auto serializeRelated(const Related& related, const model::ColumnView& relationColumn, soci::values& values) -> void
392{
393 using related_t = std::remove_cv_t<Related>;
394 const auto relatedFields = reflection::fieldPointers(related);
395
396 auto serialize = [&]<typename Index>(Index, const auto* field)
397 {
398 using field_t = std::decay_t<decltype(*field)>;
400 {
401 return;
402 }
403 else
404 {
405 constexpr auto* targetColumn = mappedColumn<related_t, SchemaType, Index::value>;
406 if constexpr (targetColumn != nullptr)
407 {
408 if (targetColumn->isPrimaryKey)
409 {
410 const auto parameterName = std::format("{}_{}", relationColumn.name, targetColumn->name);
411 setScalarFieldValue(values, parameterName, *field, targetColumn->type.value(),
412 targetColumn->maxStringLength);
413 }
414 }
415 }
416 };
417
418 utils::constexpr_for_tuple(relatedFields, serialize);
419}
420
421template <typename Related, typename SchemaType>
422auto setRelatedNull(soci::values& values, const model::ColumnView& relationColumn) -> void
423{
424 constexpr auto related = model::modelView<SchemaType, Related>();
425 for (const auto primaryKeyIndex : related->primaryKeyIndices)
426 {
427 const auto& targetColumn = related->columns[primaryKeyIndex];
428 setNullValue(values, std::format("{}_{}", relationColumn.name, targetColumn.name), targetColumn.type.value());
429 }
430}
431} // namespace detail
432
433template <typename ModelField>
435{
436 template <typename T, typename SchemaType, bool JoinedValues>
437 static auto set(const ModelField* field, const BindingPayload<T, SchemaType, JoinedValues>&,
438 const model::ColumnView& column, soci::values& values) -> void
439 {
440 if (column.isAutoIncrement)
441 {
442 return;
443 }
444
446 {
447 using related_t = std::remove_cv_t<optional_value_t<ModelField>>;
448 if constexpr (model::isNullable<ModelField>)
449 {
451 {
452 detail::serializeRelated<related_t, SchemaType>(NullableAdapter<ModelField>::value(*field), column,
453 values);
454 }
455 else
456 {
457 detail::setRelatedNull<related_t, SchemaType>(values, column);
458 }
459 }
460 else
461 {
462 detail::serializeRelated<ModelField, SchemaType>(*field, column, values);
463 }
464 }
465 else
466 {
467 setScalarFieldValue(values, std::string{column.name}, *field, column.type.value(), column.maxStringLength);
468 }
469 }
470
471 template <typename T, typename SchemaType, bool JoinedValues, std::size_t FieldIndex>
472 static auto set(const ModelField* field, const BindingPayload<T, SchemaType, JoinedValues>& payload,
473 std::integral_constant<std::size_t, FieldIndex>, soci::values& values) -> void
474 {
475 set(field, payload, payload.template columnDescriptor<FieldIndex>(), values);
476 }
477
478 template <typename T, typename SchemaType, bool JoinedValues>
479 static auto set(const ModelField* field, const BindingPayload<T, SchemaType, JoinedValues>& payload,
480 std::size_t fieldIndex, soci::values& values) -> void
481 {
482 set(field, payload, payload.columnDescriptor(fieldIndex), values);
483 }
484};
485} // namespace orm::db::binding
Internal signal for a result value that cannot be represented by the requested model or projection fi...
Definition numeric.cppm:83
auto setNullValue(soci::values &values, const std::string &name, model::ColumnType type) -> void
auto getScalarFieldValue(const auto &values, const std::string &fieldName) -> ModelField
auto validateStringLength(std::string_view text, std::optional< std::size_t > limit) -> void
auto setScalarFieldValue(soci::values &values, const std::string &fieldName, const ModelField &field, model::ColumnType columnType, std::optional< std::size_t > maxStringLength=std::nullopt) -> void
auto getEncodedScalarValue(const auto &values, const std::string &name) -> T
Definition numeric.cppm:151
auto encodeScalarValue(const T &value) -> std::string
Definition numeric.cppm:106
auto checkedNumericCast(Source value, std::string_view fieldName) -> Result
Definition numeric.cppm:229
auto getNumericValue(const auto &values, const std::string &fieldName) -> Result
Definition numeric.cppm:421
auto makeNullableValue(Value value) -> Wrapper
Definition numeric.cppm:64
auto bindTypedNull(soci::values &values, std::string_view name, const T &value) -> void
constexpr bool isNullable
Definition mapping.cppm:552
constexpr auto modelView() noexcept -> ModelView
Definition schema.cppm:120
constexpr auto fieldPointers(T &value) noexcept
constexpr auto constexpr_for_tuple(Tuple &&t, F &&f, Args... args) -> void
constexpr bool is_relation_collection_v
static auto get(ModelField *field, const BindingPayload< T, SchemaType, JoinedValues > &payload, std::size_t fieldIndex, const auto &values) -> void
static auto get(ModelField *field, const BindingPayload< T, SchemaType, JoinedValues > &, const model::ColumnView &column, const auto &values) -> void
static auto get(ModelField *field, const BindingPayload< T, SchemaType, JoinedValues > &payload, std::integral_constant< std::size_t, FieldIndex >, const auto &values) -> void
static auto set(const ModelField *field, const BindingPayload< T, SchemaType, JoinedValues > &payload, std::integral_constant< std::size_t, FieldIndex >, soci::values &values) -> void
static auto set(const ModelField *field, const BindingPayload< T, SchemaType, JoinedValues > &, const model::ColumnView &column, soci::values &values) -> void
static auto set(const ModelField *field, const BindingPayload< T, SchemaType, JoinedValues > &payload, std::size_t fieldIndex, soci::values &values) -> void
Trivially-copyable handle to one model in immutable Schema storage.
Definition views.cppm:181