ORM C++
Loading...
Searching...
No Matches
result_storage.cppm
Go to the documentation of this file.
1module;
2
3#include <algorithm>
4#include <array>
5#include <cstddef>
6#include <memory>
7#include <optional>
8#include <string>
9#include <string_view>
10#include <type_traits>
11#include <utility>
12#include <variant>
13#include <vector>
14
15export module orm:database_result_storage;
16
17import orm.reflection;
18import :foundation;
19import :model;
20import :expressions;
21import :sql;
22import :value_codec;
23import :database_numeric;
24
25namespace orm::db::binding
26{
27/**
28 * A session-bound, stable exchange buffer for one Binary16 parameter or result.
29 * The buffer and its indicator must outlive the statement using them. SQLite
30 * results additionally require typeof(value) from the same row, because SOCI's
31 * blob exchange converts other storage classes before returning the bytes.
32 */
34{
35 soci::blob blob_;
36 soci::indicator indicator_{soci::i_null};
37
38public:
39 explicit Binary16Buffer(soci::session& session) : blob_{session} {}
40
41 auto set(const std::optional<orm::Uuid>& value) -> void
42 {
43 indicator_ = value ? soci::i_ok : soci::i_null;
44 blob_.trim(0);
45 if (value)
46 {
47 // SOCI's blob API takes `const char*`; `std::byte` carries the same
48 // representation and is the type the UUID codec exposes.
49 const auto* bytes = reinterpret_cast<const char*>(value->bytes().data());
50 if (blob_.write_from_start(bytes, value->bytes().size()) != value->bytes().size())
51 throw ConversionError{"Could not write a complete Binary16 value"};
52 }
53 }
54
55 auto exchangeUse(soci::statement& statement, const std::string& name) -> void;
56 auto exchangeInto(soci::statement& statement) -> void;
57
58 [[nodiscard]] auto indicator() const noexcept -> soci::indicator
59 {
60 return indicator_;
61 }
62
63 [[nodiscard]] auto read(BackendType backend, std::string_view sqliteStorageClass = {}) -> std::optional<orm::Uuid>
64 {
65 if (backend != BackendType::Sqlite && backend != BackendType::Mysql)
66 throw ConversionError{"Binary16 is unavailable for this backend"};
67 if (indicator_ == soci::i_null)
68 return std::nullopt;
69 if (indicator_ != soci::i_ok)
70 throw ConversionError{"A Binary16 result was truncated by its transport"};
71 if (backend == BackendType::Sqlite && sqliteStorageClass != "blob")
72 throw ConversionError{"A Binary16 result is not a SQLite BLOB"};
73 std::array<std::byte, 16> bytes{};
74 auto* buffer = reinterpret_cast<char*>(bytes.data());
75 if (blob_.get_len() != bytes.size() || blob_.read_from_start(buffer, bytes.size()) != bytes.size())
76 throw ConversionError{"A Binary16 result must contain exactly 16 bytes"};
77 return orm::Uuid{bytes};
78 }
79};
80
81/** Owns the regular SOCI values and session-bound Binary16 input buffers. */
83{
84 struct BinaryParameter
85 {
86 std::string name;
87 Binary16Buffer buffer;
88 const BackendRuntime& runtime;
89
90 BinaryParameter(std::string nameInit, soci::session& session, const BackendRuntime& runtimeInit)
91 : name{std::move(nameInit)}, buffer{session}, runtime{runtimeInit}
92 {
93 }
94 };
95
96 soci::values values_;
97 soci::values* borrowedValues_{};
98 std::vector<std::unique_ptr<BinaryParameter>> binaries_;
99
100public:
101 StatementBindings() = default;
102 explicit StatementBindings(soci::values& values) : borrowedValues_{&values} {}
103
104 auto add(soci::session& session, const BackendRuntime& runtime, std::string_view name,
105 const BoundValue& bound) -> void
106 {
107 if (bound.uuidStorage == model::UuidStorage::Native)
108 {
109 runtime.bind(values(), name, bound);
110 return;
111 }
112 if (bound.uuidStorage == model::UuidStorage::Text36)
113 {
114 if (bound.logicalType != model::ColumnType::Uuid)
115 throw ConversionError{"Text36 requires a logical UUID parameter"};
116 BoundValue text{.logicalType = model::ColumnType::String, .value = std::nullopt};
117 if (bound.value)
118 {
119 const auto* uuid = std::get_if<orm::Uuid>(&*bound.value);
120 if (!uuid)
121 throw ConversionError{"A Text36 parameter has incompatible storage"};
122 text.value = orm::detail::values::format(*uuid);
123 }
124 runtime.bind(values(), name, text);
125 return;
126 }
127 if (bound.uuidStorage != model::UuidStorage::Binary16)
128 throw ConversionError{"Invalid UUID storage representation"};
129 if (bound.logicalType != model::ColumnType::Uuid)
130 throw ConversionError{"Binary16 requires a logical UUID parameter"};
131
132 std::optional<orm::Uuid> value;
133 if (bound.value)
134 {
135 const auto* uuid = std::get_if<orm::Uuid>(&*bound.value);
136 if (!uuid)
137 throw ConversionError{"A Binary16 parameter has incompatible storage"};
138 value = *uuid;
139 }
140 auto binary = std::make_unique<BinaryParameter>(std::string{name}, session, runtime);
141 binary->buffer.set(value);
142 binaries_.push_back(std::move(binary));
143 }
144
145 auto add(soci::session& session, const BackendRuntime& runtime, const StatementParameter& parameter) -> void
146 {
147 add(session, runtime, parameter.name, parameter.getBoundValue());
148 }
149
150 [[nodiscard]] auto hasBinary() const noexcept -> bool
151 {
152 return !binaries_.empty();
153 }
154
155 auto exchange(soci::statement& statement) -> void;
156
157 auto values() noexcept -> soci::values&
158 {
159 return borrowedValues_ ? *borrowedValues_ : values_;
160 }
161};
162
164{
165 std::string alias;
167 std::optional<model::ColumnType> requestedType = std::nullopt;
168 const model::ColumnView* column = nullptr;
169};
170
171inline auto isEncodedResultType(model::ColumnType type) noexcept -> bool
172{
173 using enum model::ColumnType;
174 return type == Date || type == TimeOfDay || type == LocalDateTime || type == UtcTimestamp || type == Uuid;
175}
176
177inline auto hasEncodedResult(const std::vector<ResultColumn>& columns) -> bool
178{
179 return std::ranges::any_of(columns,
180 [](const auto& column)
181 {
182 return isEncodedResultType(column.logicalType) ||
183 (column.requestedType && isEncodedResultType(*column.requestedType));
184 });
185}
186
187inline auto validateResultIndicator(soci::indicator indicator) -> void
188{
189 if (indicator != soci::i_ok && indicator != soci::i_null)
190 throw ConversionError{"A database result was truncated by its transport"};
191}
192
193// Keep this ordering identical to emitSqlFullFields, including the flattened
194// to-one aliases used by joined and non-joined hydration.
195inline auto modelResultColumns(model::ModelView model, bool joined) -> std::vector<ResultColumn>
196{
197 std::vector<ResultColumn> result;
198 for (const auto& column : model->columns)
199 {
200 if (column.kind == model::FieldKind::Scalar)
201 {
202 result.push_back({std::string{model->tableName} + "_" + std::string{column.name}, column.type.value(),
203 std::nullopt, &column});
204 }
205 else
206 {
207 const auto target = model.resolveTarget(column);
208 if (!target)
209 throw ConversionError{"A related result model is not available in its schema"};
210 for (const auto& child : target->columns)
211 {
212 if (joined || child.isPrimaryKey)
213 {
214 const auto prefix = joined ? std::string{column.name} :
215 std::string{model->tableName} + "_" + std::string{column.name};
216 result.push_back(
217 {prefix + "_" + std::string{child.name}, child.type.value(), std::nullopt, &child});
218 }
219 }
220 }
221 }
222 return result;
223}
224
225inline auto resultSource(const query::detail::Column& column) -> db::detail::SqlSource
226{
227 return db::detail::parseSqlSource(column.getPath());
228}
229
230inline auto resultSource(const query::detail::AggregateExpression& expression) -> db::detail::SqlSource
231{
232 auto source = expression.column ? resultSource(*expression.column) : db::detail::SqlSource{};
233 source.isAggregate = true;
234 source.function = expression.function;
235 return source;
236}
237
238inline auto resultSourceType(const db::detail::SqlSource& source, model::ModelView model) -> model::ColumnType
239{
240 if (source.isAggregate)
241 {
242 using enum query::detail::AggregateFunction;
243 if (source.function == Count || source.function == CountAll)
245 // The existing emitter transports SUM and AVG through an explicit text
246 // result to preserve decimal conversion checks.
247 if (source.function == Sum || source.function == Avg)
249 }
250 return db::detail::resolveSqlColumn(source, model).logicalType;
251}
252
253template <typename Result, typename Projections>
254auto projectionResultColumns(model::ModelView model, const Projections& projections) -> std::vector<ResultColumn>
255{
256 std::vector<ResultColumn> result;
257 result.reserve(projections.size());
258 for (const auto& projection : projections)
259 {
260 if constexpr (requires { projection.alias; })
261 {
262 result.push_back({std::string{projection.alias}, resultSourceType(projection.source, model)});
263 if (result.back().logicalType == model::ColumnType::Uuid)
264 result.back().column = db::detail::resolveSqlColumn(projection.source, model).column;
265 }
266 else
267 {
268 const auto source = std::visit([](const auto& value) { return resultSource(value); }, projection.source);
269 result.push_back({projection.resultField, resultSourceType(source, model)});
270 if (result.back().logicalType == model::ColumnType::Uuid)
271 result.back().column = db::detail::resolveSqlColumn(source, model).column;
272 }
273 [&]<std::size_t... Indices>(std::index_sequence<Indices...>)
274 {
275 constexpr auto fields = reflection::fields<Result>();
276 auto matchField = [&]<std::size_t Index>()
277 {
279 if constexpr (requires { model::LogicalTypeTraits<field_t>::value; })
280 if (result.back().alias == fields[Index].name)
281 result.back().requestedType = model::LogicalTypeTraits<field_t>::value;
282 };
283 (matchField.template operator()<Indices>(), ...);
284 }(std::make_index_sequence<reflection::fieldCount<Result>>{});
285 }
286 return result;
287}
288
289/**
290 * Owns stable per-column buffers for explicit SOCI exchanges. New scalar types
291 * always use into(string, indicator), bypassing dynamic row/date conversion.
292 * Its row view retains the existing hydration and numeric checks without
293 * allocating unbound soci::values holders, whose lifetime SOCI cannot manage.
294 */
296{
297 using Storage = std::variant<int, long long, unsigned long long, double, std::string>;
298
299 struct Buffer
300 {
301 ResultColumn column;
302 Storage value;
303 soci::indicator indicator = soci::i_null;
304 std::unique_ptr<Binary16Buffer> binary;
305 std::string sqliteStorageClass;
306 };
307
308 std::vector<std::unique_ptr<Buffer>> buffers;
309
310 auto find(std::string_view alias) const -> const Buffer&
311 {
312 const auto found =
313 std::ranges::find_if(buffers, [&](const auto& buffer) { return buffer->column.alias == alias; });
314 if (found == buffers.end())
315 throw ConversionError{"The requested result alias is missing"};
316 return **found;
317 }
318
319 struct NoResultValidation
320 {
321 auto operator()(const BoundValue&) const noexcept -> void {}
322 };
323
324 static auto decodedResult(model::ColumnType type, std::string_view text) -> query::QueryValue::Value
325 {
326 using enum model::ColumnType;
327 // read() calls this only after isEncodedResultType accepts the logical type.
328 if (type == Date)
329 return decodeScalarValue<orm::Date>(text);
330 if (type == TimeOfDay)
332 if (type == LocalDateTime)
334 if (type == UtcTimestamp)
336 return decodeScalarValue<orm::Uuid>(text);
337 }
338
339 static auto storageFor(model::ColumnType type) -> Storage
340 {
341 using enum model::ColumnType;
342 switch (type)
343 {
344 case Bool:
345 case Char:
346 case UnsignedChar:
347 case Short:
348 case UnsignedShort:
349 case Int:
350 return int{};
351 case UnsignedInt:
352 case UnsignedLongLong:
353 return static_cast<unsigned long long>(0);
354 case LongLong:
355 return static_cast<long long>(0);
356 case Float:
357 case Double:
358 return double{};
359 case String:
360 case Date:
361 case TimeOfDay:
362 case LocalDateTime:
363 case UtcTimestamp:
364 case Uuid:
365 return std::string{};
366 }
367 throw ConversionError{"Unsupported result column type"};
368 }
369
370public:
372 {
373 decltype(soci::dt_string) type;
374 auto get_data_type() const noexcept -> decltype(soci::dt_string)
375 {
376 return type;
377 }
378 };
379
380 auto get_indicator(std::string_view alias) const -> soci::indicator
381 {
382 return find(alias).indicator;
383 }
384
385 auto get_properties(std::string_view alias) const -> Properties
386 {
387 return std::visit(
388 [](const auto& value) -> Properties
389 {
390 using T = std::remove_cvref_t<decltype(value)>;
391 if constexpr (std::is_same_v<T, int>)
392 return {soci::dt_integer};
393 else if constexpr (std::is_same_v<T, long long>)
394 return {soci::dt_long_long};
395 else if constexpr (std::is_same_v<T, unsigned long long>)
396 return {soci::dt_unsigned_long_long};
397 else if constexpr (std::is_same_v<T, double>)
398 return {soci::dt_double};
399 else
400 return {soci::dt_string};
401 },
402 find(alias).value);
403 }
404
405 template <typename T>
406 auto get(std::string_view alias) const -> T
407 {
408 const auto& buffer = find(alias);
409 if (buffer.indicator == soci::i_null)
410 throw ConversionError{"A non-null result field contains NULL"};
411 const auto* value = std::get_if<T>(&buffer.value);
412 if (!value)
413 throw ConversionError{"The result field has a different storage representation"};
414 return *value;
415 }
416
417 explicit TypedResultStorage(std::vector<ResultColumn> columns)
418 {
419 buffers.reserve(columns.size());
420 for (auto& column : columns)
421 {
422 if (column.requestedType &&
423 (isEncodedResultType(column.logicalType) || isEncodedResultType(*column.requestedType)) &&
424 column.logicalType != *column.requestedType)
425 throw ConversionError{"A projected scalar type does not match its requested result field"};
426 auto storage = storageFor(column.logicalType);
427 buffers.push_back(
428 std::make_unique<Buffer>(Buffer{std::move(column), std::move(storage), soci::i_null, nullptr, {}}));
429 }
430 }
431
432 template <typename Consume, typename Validate = NoResultValidation>
433 auto read(soci::session& session, std::string_view sql, StatementBindings& parameters, Consume consume,
434 std::optional<BackendType> backend = std::nullopt, Validate validate = {}) -> void
435 {
436 const bool signedSqlIntegers =
437 backend && (*backend == BackendType::Postgres || *backend == BackendType::Sqlite);
438 // Preserve the SQL sign until checkedNumericCast runs; an unsigned
439 // SOCI exchange can turn -1 into the maximum unsigned value.
440 for (auto& buffer : buffers)
441 {
442 buffer->binary.reset();
443 buffer->sqliteStorageClass.clear();
444 if (buffer->column.logicalType == model::ColumnType::UnsignedInt ||
445 buffer->column.logicalType == model::ColumnType::UnsignedLongLong)
446 buffer->value = signedSqlIntegers ? Storage{static_cast<long long>(0)} :
447 Storage{static_cast<unsigned long long>(0)};
448 if (backend && buffer->column.column && buffer->column.logicalType == model::ColumnType::Uuid &&
449 buffer->column.column->uuidStorage(*backend) == model::UuidStorage::Binary16)
450 buffer->binary = std::make_unique<Binary16Buffer>(session);
451 }
452 soci::statement statement{session};
453 statement.alloc();
454 statement.prepare(std::string{sql});
455 parameters.exchange(statement);
456 for (auto& buffer : buffers)
457 {
458 if (buffer->binary)
459 buffer->binary->exchangeInto(statement);
460 else
461 std::visit([&](auto& value) { statement.exchange(soci::into(value, buffer->indicator)); },
462 buffer->value);
463 }
464 if (backend && *backend == BackendType::Sqlite)
465 for (auto& buffer : buffers)
466 if (buffer->binary || (buffer->column.column && buffer->column.logicalType == model::ColumnType::Uuid &&
467 buffer->column.column->uuidStorage(*backend) == model::UuidStorage::Text36))
468 statement.exchange(soci::into(buffer->sqliteStorageClass));
469 statement.define_and_bind();
470 statement.execute();
471 while (statement.fetch())
472 {
473 for (const auto& buffer : buffers)
474 {
475 // A Text36 column stores a canonical TEXT UUID, so the native UUID
476 // validation (Postgres/MariaDB only) must not apply to its result.
477 const bool text36Result = backend && buffer->column.logicalType == model::ColumnType::Uuid &&
478 buffer->column.column != nullptr &&
479 buffer->column.column->uuidStorage(*backend) == model::UuidStorage::Text36;
480 if (buffer->binary)
481 {
482 const auto value = buffer->binary->read(*backend, buffer->sqliteStorageClass);
483 buffer->indicator = buffer->binary->indicator();
484 if (value)
485 buffer->value = value->toString();
486 }
487 else if (backend && *backend == BackendType::Sqlite &&
488 buffer->column.logicalType == model::ColumnType::Uuid && buffer->column.column != nullptr &&
489 buffer->column.column->uuidStorage(*backend) == model::UuidStorage::Text36 &&
490 buffer->indicator != soci::i_null && buffer->sqliteStorageClass != "text")
491 {
492 throw ConversionError{"A Text36 result is not a SQLite TEXT value"};
493 }
494 validateResultIndicator(buffer->indicator);
495 if (buffer->indicator != soci::i_null && isEncodedResultType(buffer->column.logicalType))
496 {
497 auto value = decodedResult(buffer->column.logicalType, std::get<std::string>(buffer->value));
498 if (backend && !buffer->binary && !text36Result)
499 {
500 try
501 {
502 std::visit(
503 [&](const auto& scalar)
504 {
505 if constexpr (SociEncodedValue<std::remove_cvref_t<decltype(scalar)>>)
506 orm::detail::values::validateNative(scalar, *backend);
507 },
508 value);
509 }
510 catch (const std::invalid_argument&)
511 {
512 throw ConversionError{"A database result exceeds its native scalar type range"};
513 }
514 }
515 validate(BoundValue{.logicalType = buffer->column.logicalType,
516 .value = std::move(value),
517 .uuidStorage = buffer->binary ?
519 (backend && buffer->column.column != nullptr &&
520 buffer->column.column->uuidStorage(*backend) ==
524 }
525 }
526 consume(*this);
527 }
528 }
529
530 template <typename Consume, typename Validate = NoResultValidation>
531 auto read(soci::session& session, std::string_view sql, soci::values& parameters, Consume consume,
532 std::optional<BackendType> backend = std::nullopt, Validate validate = {}) -> void
533 {
534 StatementBindings bindings{parameters};
535 read(session, sql, bindings, std::move(consume), backend, std::move(validate));
536 }
537};
538} // namespace orm::db::binding
auto exchangeInto(soci::statement &statement) -> void
auto set(const std::optional< orm::Uuid > &value) -> void
auto indicator() const noexcept -> soci::indicator
Binary16Buffer(soci::session &session)
auto exchangeUse(soci::statement &statement, const std::string &name) -> void
auto read(BackendType backend, std::string_view sqliteStorageClass={}) -> std::optional< orm::Uuid >
Internal signal for a result value that cannot be represented by the requested model or projection fi...
Definition numeric.cppm:83
auto hasBinary() const noexcept -> bool
auto values() noexcept -> soci::values &
auto add(soci::session &session, const BackendRuntime &runtime, std::string_view name, const BoundValue &bound) -> void
auto add(soci::session &session, const BackendRuntime &runtime, const StatementParameter &parameter) -> void
auto exchange(soci::statement &statement) -> void
auto get_indicator(std::string_view alias) const -> soci::indicator
auto get(std::string_view alias) const -> T
auto read(soci::session &session, std::string_view sql, soci::values &parameters, Consume consume, std::optional< BackendType > backend=std::nullopt, Validate validate={}) -> void
auto get_properties(std::string_view alias) const -> Properties
TypedResultStorage(std::vector< ResultColumn > columns)
auto read(soci::session &session, std::string_view sql, StatementBindings &parameters, Consume consume, std::optional< BackendType > backend=std::nullopt, Validate validate={}) -> void
std::variant< int, long long, unsigned long long, double, std::string, Date, TimeOfDay, LocalDateTime, UtcTimestamp, Uuid > Value
Definition value.cppm:35
auto isEncodedResultType(model::ColumnType type) noexcept -> bool
auto resultSource(const query::detail::Column &column) -> db::detail::SqlSource
auto validateResultIndicator(soci::indicator indicator) -> void
auto decodeScalarValue(std::string_view text) -> T
Definition numeric.cppm:127
auto modelResultColumns(model::ModelView model, bool joined) -> std::vector< ResultColumn >
auto hasEncodedResult(const std::vector< ResultColumn > &columns) -> bool
auto projectionResultColumns(model::ModelView model, const Projections &projections) -> std::vector< ResultColumn >
typename OptionalValue< std::remove_cv_t< T > >::Type optional_value_t
Definition numeric.cppm:61
auto resultSourceType(const db::detail::SqlSource &source, model::ModelView model) -> model::ColumnType
BackendType
Definition types.cppm:62
consteval auto fields() noexcept
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
std::optional< query::QueryValue::Value > value
const model::ColumnView * column
std::optional< model::ColumnType > requestedType
auto get_data_type() const noexcept -> decltype(soci::dt_string)
Trivially-copyable handle to one model in immutable Schema storage.
Definition views.cppm:181