ORM C++
Loading...
Searching...
No Matches
numeric.cppm
Go to the documentation of this file.
1module;
2
3#include <bit>
4#include <charconv>
5#include <cmath>
6#include <cstddef>
7#include <cstdint>
8#include <exception>
9#include <limits>
10#include <new>
11#include <optional>
12#include <sstream>
13#include <stdexcept>
14#include <string>
15#include <string_view>
16#include <system_error>
17#include <type_traits>
18#include <utility>
19
20export module orm:database_numeric;
21
22import :foundation;
23import :value_codec;
24export import :database_soci;
25
27{
28template <typename ModelField, typename... Types>
29concept IsOneOfTypes = (std::is_same_v<ModelField, Types> || ...);
30
31template <typename ModelField>
34 (std::is_same_v<ModelField, long> and sizeof(long) <= sizeof(int));
35
36template <typename ModelField>
37concept SociConvertableToLongLong = std::is_same_v<ModelField, long> and sizeof(long) > sizeof(int);
38
39template <typename ModelField>
41
42template <typename ModelField>
44
45template <typename ModelField>
47
48template <typename T>
50{
51 using Type = T;
52};
53
54template <NullableAdaptable T>
56{
58};
59
60template <typename T>
62
63template <typename Wrapper, typename Value>
64auto makeNullableValue(Value value) -> Wrapper
65{
66 using contained_t = typename NullableAdapter<Wrapper>::Value;
67 if constexpr (std::is_move_constructible_v<contained_t>)
68 return NullableAdapter<Wrapper>::make(std::move(value));
69 else
71}
72
73template <typename SchemaType, typename ModelField>
74concept SchemaModel = SchemaType::template contains<std::remove_cv_t<optional_value_t<ModelField>>>;
75} // namespace orm::db::binding
76namespace orm::db::binding
77{
78/**
79 * @brief Internal signal for a result value that cannot be represented by the
80 * requested model or projection field without loss.
81 */
82class ConversionError final : public std::runtime_error
83{
84public:
85 explicit ConversionError(std::string message) : std::runtime_error{std::move(message)} {}
86};
87
88template <typename T>
91
92template <UuidAdaptable T>
93auto canonicalUuid(const T& value) -> Uuid
94{
95 try
96 {
97 return UuidAdapter<T>::toUuid(value);
98 }
99 catch (const std::invalid_argument&)
100 {
101 throw ConversionError{"A UUID value was rejected by its adapter"};
102 }
103}
104
105template <SociEncodedValue T>
106auto encodeScalarValue(const T& value) -> std::string
107{
108 try
109 {
110 if constexpr (UuidAdaptable<T>)
111 {
112 return orm::detail::values::format(canonicalUuid(value));
113 }
114 else
115 {
116 orm::detail::values::validate(value);
117 return orm::detail::values::format(value);
118 }
119 }
120 catch (const std::invalid_argument&)
121 {
122 throw ConversionError{"A value cannot be represented by its logical column type"};
123 }
124}
125
126template <SociEncodedValue T>
127auto decodeScalarValue(std::string_view text) -> T
128{
129 try
130 {
131 if constexpr (std::is_same_v<T, Date>)
132 return orm::detail::values::parseDate(text);
133 else if constexpr (std::is_same_v<T, TimeOfDay>)
134 return orm::detail::values::parseTimeOfDay(text);
135 else if constexpr (std::is_same_v<T, LocalDateTime>)
136 return orm::detail::values::parseLocalDateTime(text);
137 else if constexpr (std::is_same_v<T, UtcTimestamp>)
138 return orm::detail::values::parseUtcTimestamp(text);
139 else if constexpr (UuidAdaptable<T>)
141 else
142 return Uuid::parse(text);
143 }
144 catch (const std::invalid_argument&)
145 {
146 throw ConversionError{"A database value cannot be represented by its logical column type"};
147 }
148}
149
150template <SociEncodedValue T>
151auto getEncodedScalarValue(const auto& values, const std::string& name) -> T
152{
153 std::string value;
154 try
155 {
156 value = values.template get<std::string>(name);
157 }
158 catch (const std::bad_alloc&)
159 {
160 throw;
161 }
162 catch (const std::exception&)
163 {
164 throw ConversionError{"A database value has an incompatible result representation"};
165 }
166 return decodeScalarValue<T>(value);
167}
168} // namespace orm::db::binding
169namespace orm::db::binding
170{
171template <typename Result, typename Source>
172// requires(std::is_integral_v<Result> and std::is_integral_v<Source> and
173// not std::is_same_v<std::remove_cv_t<Result>, bool> and not std::is_same_v<std::remove_cv_t<Source>, bool>)
174[[nodiscard]] constexpr auto isIntegralInRange(Source value) noexcept -> bool
175{
176 using result_t = std::remove_cv_t<Result>;
177 using source_t = std::remove_cv_t<Source>;
178
179 if constexpr (std::is_signed_v<result_t> == std::is_signed_v<source_t>)
180 {
181 if constexpr (std::numeric_limits<result_t>::digits >= std::numeric_limits<source_t>::digits)
182 {
183 return true;
184 }
185 else
186 {
187 return value >= static_cast<source_t>(std::numeric_limits<result_t>::lowest()) and
188 value <= static_cast<source_t>(std::numeric_limits<result_t>::max());
189 }
190 }
191 else if constexpr (std::is_signed_v<source_t>)
192 {
193 if (value < 0)
194 {
195 return false;
196 }
197
198 if constexpr (std::numeric_limits<result_t>::digits >= std::numeric_limits<source_t>::digits)
199 {
200 return true;
201 }
202 else
203 {
204 using unsigned_source_t = std::make_unsigned_t<source_t>;
205 return static_cast<unsigned_source_t>(value) <=
206 static_cast<unsigned_source_t>(std::numeric_limits<result_t>::max());
207 }
208 }
209 else
210 {
211 if constexpr (std::numeric_limits<result_t>::digits >= std::numeric_limits<source_t>::digits)
212 {
213 return true;
214 }
215 else
216 {
217 return value <= static_cast<source_t>(std::numeric_limits<result_t>::max());
218 }
219 }
220}
221
222[[noreturn]] inline auto throwLossyNumericConversion(std::string_view fieldName) -> void
223{
224 throw ConversionError{"Cannot convert numeric field without data loss: " + std::string{fieldName}};
225}
226
227template <typename Result, typename Source>
228// requires(std::is_arithmetic_v<Result> and std::is_arithmetic_v<Source>)
229auto checkedNumericCast(Source value, std::string_view fieldName) -> Result
230{
231 if constexpr (std::is_floating_point_v<Source>)
232 {
233 if (not std::isfinite(value))
234 {
236 }
237 }
238
239 if constexpr (std::is_integral_v<Result> and std::is_integral_v<Source>)
240 {
241 if constexpr (std::is_same_v<std::remove_cv_t<Result>, bool>)
242 {
243 if (value != 0 and value != 1)
244 {
246 }
247 }
248 else if constexpr (not std::is_same_v<std::remove_cv_t<Source>, bool>)
249 {
250 if (not isIntegralInRange<Result>(value))
251 {
253 }
254 }
255
256 return static_cast<Result>(value);
257 }
258 else if constexpr (std::is_integral_v<Result> and std::is_floating_point_v<Source>)
259 {
260 const auto numericValue = static_cast<long double>(value);
261 const auto upperExclusive = std::ldexp(1.0L, std::numeric_limits<Result>::digits);
262 const auto lowerInclusive = std::is_signed_v<Result> ? -upperExclusive : 0.0L;
263
264 if (std::trunc(numericValue) != numericValue or numericValue < lowerInclusive or
265 numericValue >= upperExclusive or
266 (std::is_same_v<std::remove_cv_t<Result>, bool> and numericValue != 0.0L and numericValue != 1.0L))
267 {
269 }
270
271 return static_cast<Result>(value);
272 }
273 else if constexpr (std::is_floating_point_v<Result> and std::is_integral_v<Source>)
274 {
275 const auto numericValue = static_cast<long double>(value);
276
277 if (numericValue < static_cast<long double>(std::numeric_limits<Result>::lowest()) or
278 numericValue > static_cast<long double>(std::numeric_limits<Result>::max()))
279 {
281 }
282
283 if constexpr (not std::is_same_v<std::remove_cv_t<Source>, bool>)
284 {
285 using unsigned_source_t = std::make_unsigned_t<Source>;
286 const auto unsignedValue = static_cast<unsigned_source_t>(value);
287 auto magnitude = unsignedValue;
288
289 if constexpr (std::is_signed_v<Source>)
290 {
291 if (value < 0)
292 {
293 magnitude = unsigned_source_t{} - unsignedValue;
294 }
295 }
296
297 if (magnitude != 0)
298 {
299 const auto significantBits = std::bit_width(magnitude) - std::countr_zero(magnitude);
300
301 if (significantBits > std::numeric_limits<Result>::digits)
302 {
304 }
305 }
306 }
307
308 return static_cast<Result>(value);
309 }
310 else if constexpr (std::is_floating_point_v<Result> and std::is_floating_point_v<Source> and
311 std::numeric_limits<Result>::digits < std::numeric_limits<Source>::digits)
312 {
313 if (value < static_cast<Source>(std::numeric_limits<Result>::lowest()) or
314 value > static_cast<Source>(std::numeric_limits<Result>::max()))
315 {
317 }
318
319 const auto converted = static_cast<Result>(value);
320
321 if (static_cast<Source>(converted) != value)
322 {
324 }
325
326 return converted;
327 }
328 else
329 {
330 return static_cast<Result>(value);
331 }
332}
333} // namespace orm::db::binding
334namespace orm::db::binding
335{
336template <typename Result>
337// requires std::is_arithmetic_v<Result>
338auto parseNumericValue(std::string_view value, std::string_view fieldName) -> Result
339{
340 const auto storedValue = std::string{value};
341
342 try
343 {
344 if constexpr (std::is_floating_point_v<Result>)
345 {
346 double parsed{};
347 const auto* const end = storedValue.data() + storedValue.size();
348 const auto [parsedEnd, error] =
349 std::from_chars(storedValue.data(), end, parsed, std::chars_format::general);
350
351 if (error != std::errc{} or parsedEnd != end)
352 {
353 throw ConversionError{"Cannot hydrate numeric field: " + std::string{fieldName}};
354 }
355
356 return checkedNumericCast<Result>(parsed, fieldName);
357 }
358 else if constexpr (std::is_unsigned_v<Result>)
359 {
360 std::size_t parsedCharacters{};
361 const auto firstNonWhitespace = storedValue.find_first_not_of(" \f\n\r\t\v");
362
363 if (firstNonWhitespace != std::string::npos and storedValue[firstNonWhitespace] == '-')
364 {
365 throw ConversionError{"Cannot hydrate numeric field: " + std::string{fieldName}};
366 }
367
368 const auto parsed = std::stoull(storedValue, &parsedCharacters);
369
370 if (parsedCharacters != storedValue.size())
371 {
372 throw ConversionError{"Cannot hydrate numeric field: " + std::string{fieldName}};
373 }
374
375 return checkedNumericCast<Result>(parsed, fieldName);
376 }
377 else
378 {
379 std::size_t parsedCharacters{};
380 const auto parsed = std::stoll(storedValue, &parsedCharacters);
381
382 if (parsedCharacters != storedValue.size())
383 {
384 throw ConversionError{"Cannot hydrate numeric field: " + std::string{fieldName}};
385 }
386
387 return checkedNumericCast<Result>(parsed, fieldName);
388 }
389 }
390 catch (const ConversionError&)
391 {
392 throw;
393 }
394 catch (const std::exception&)
395 {
396 throw ConversionError{"Cannot hydrate numeric field: " + std::string{fieldName}};
397 }
398}
399
400template <typename Result, typename Stored>
401// requires(std::is_arithmetic_v<Result> and std::is_arithmetic_v<Stored>)
402auto tryGetNumericValue(Result* result, const auto& values, const std::string& fieldName) -> bool
403{
404 try
405 {
406 *result = checkedNumericCast<Result>(values.template get<Stored>(fieldName), fieldName);
407 return true;
408 }
409 catch (const ConversionError&)
410 {
411 throw;
412 }
413 catch (const std::exception&)
414 {
415 return false;
416 }
417}
418
419template <typename Result>
420// requires std::is_arithmetic_v<Result>
421auto getNumericValue(const auto& values, const std::string& fieldName) -> Result
422{
423 auto convertStoredValue = [&values, &fieldName]<typename Stored>() -> Result
424 { return checkedNumericCast<Result>(values.template get<Stored>(fieldName), fieldName); };
425
426 try
427 {
428 switch (values.get_properties(fieldName).get_data_type())
429 {
430 case soci::dt_integer:
431 return convertStoredValue.template operator()<int>();
432 case soci::dt_long_long:
433 return convertStoredValue.template operator()<long long>();
434 case soci::dt_unsigned_long_long:
435 return convertStoredValue.template operator()<unsigned long long>();
436 case soci::dt_double:
437 return convertStoredValue.template operator()<double>();
438 case soci::dt_string:
439 return parseNumericValue<Result>(values.template get<std::string>(fieldName), fieldName);
440 default:
441 throw ConversionError{"Cannot hydrate numeric field: " + fieldName};
442 }
443 }
444 catch (const ConversionError&)
445 {
446 throw;
447 }
448 catch (const std::exception&)
449 {
450 // Locally assembled soci::values instances have no column properties.
451 // Try the canonical SOCI arithmetic holders used by orm-cxx instead.
452 }
453 auto result = Result{};
454
455 if (tryGetNumericValue<Result, int>(&result, values, fieldName) or
456 tryGetNumericValue<Result, long long>(&result, values, fieldName) or
457 tryGetNumericValue<Result, unsigned long long>(&result, values, fieldName) or
458 tryGetNumericValue<Result, double>(&result, values, fieldName))
459 {
460 return result;
461 }
462
463 try
464 {
465 return parseNumericValue<Result>(values.template get<std::string>(fieldName), fieldName);
466 }
467 catch (const ConversionError&)
468 {
469 throw;
470 }
471 catch (const std::exception&)
472 {
473 throw ConversionError{"Cannot hydrate numeric field: " + fieldName};
474 }
475}
476} // namespace orm::db::binding
static auto parse(std::string_view text) -> Uuid
Internal signal for a result value that cannot be represented by the requested model or projection fi...
Definition numeric.cppm:83
ConversionError(std::string message)
Definition numeric.cppm:85
auto throwLossyNumericConversion(std::string_view fieldName) -> void
Definition numeric.cppm:222
auto getEncodedScalarValue(const auto &values, const std::string &name) -> T
Definition numeric.cppm:151
auto decodeScalarValue(std::string_view text) -> T
Definition numeric.cppm:127
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 tryGetNumericValue(Result *result, const auto &values, const std::string &fieldName) -> bool
Definition numeric.cppm:402
auto makeNullableValue(Value value) -> Wrapper
Definition numeric.cppm:64
auto canonicalUuid(const T &value) -> Uuid
Definition numeric.cppm:93
constexpr auto isIntegralInRange(Source value) noexcept -> bool
Definition numeric.cppm:174
auto parseNumericValue(std::string_view value, std::string_view fieldName) -> Result
Definition numeric.cppm:338
typename OptionalValue< std::remove_cv_t< T > >::Type optional_value_t
Definition numeric.cppm:61
std::chrono::year_month_day Date
Definition values.cppm:20
std::chrono::local_time< std::chrono::microseconds > LocalDateTime
Definition values.cppm:23
std::chrono::sys_time< std::chrono::microseconds > UtcTimestamp
Definition values.cppm:26
typename NullableAdapter< T >::Value Type
Definition numeric.cppm:57