ORM C++
Loading...
Searching...
No Matches
payload.cppm
Go to the documentation of this file.
1module;
2
3#include <algorithm>
4#include <compare>
5#include <cstddef>
6#include <format>
7#include <optional>
8#include <sstream>
9#include <stdexcept>
10#include <string>
11#include <type_traits>
12#include <utility>
13#include <variant>
14#include <vector>
15
16export module orm:database_payload;
17
18import orm.reflection;
19import :foundation;
20import :model;
21import :expressions;
22import :sql_contracts;
23export import :database_numeric;
24
25namespace orm::db::binding
26{
27namespace detail
28{
29template <typename T, typename SchemaType, std::size_t FieldIndex>
30[[nodiscard]] consteval auto mappedColumnPointer() noexcept -> const model::ColumnView*
31{
32 constexpr auto descriptor = model::modelView<SchemaType, T>();
33 for (const auto& column : descriptor->columns)
34 {
35 if (column.fieldIndex == FieldIndex)
36 {
37 return &column;
38 }
39 }
40 return nullptr;
41}
42
43template <typename T, typename SchemaType, std::size_t FieldIndex>
44inline constexpr auto mappedColumn = mappedColumnPointer<T, SchemaType, FieldIndex>();
45
46template <typename T, typename SchemaType, std::size_t FieldIndex>
47[[nodiscard]] constexpr auto columnForField() noexcept -> const model::ColumnView&
48{
49 static_assert(mappedColumn<T, SchemaType, FieldIndex> != nullptr,
50 "A bound field must have a column descriptor in the selected schema");
51 return *mappedColumn<T, SchemaType, FieldIndex>;
52}
53
54template <typename T, typename SchemaType>
55[[nodiscard]] constexpr auto columnForField(std::size_t fieldIndex) -> const model::ColumnView&
56{
57 constexpr auto descriptor = model::modelView<SchemaType, T>();
58 for (const auto& column : descriptor->columns)
59 {
60 if (column.fieldIndex == fieldIndex)
61 {
62 return column;
63 }
64 }
65 throw std::invalid_argument{"A bound field has no column descriptor in the selected schema"};
66}
67} // namespace detail
68
69template <typename T, typename SchemaType, bool JoinedValues = false>
71{
72 static_assert(SchemaType::template contains<std::remove_cv_t<T>>, "BindingPayload model must belong to its Schema");
73
74 mutable T value{};
75 inline static constexpr bool joinedValues = JoinedValues;
76
77 [[nodiscard]] static constexpr auto modelDescriptor() noexcept -> model::ModelView
78 {
80 }
81
82 template <std::size_t FieldIndex>
83 [[nodiscard]] static constexpr auto columnDescriptor() noexcept -> const model::ColumnView&
84 {
85 return detail::columnForField<std::remove_cv_t<T>, SchemaType, FieldIndex>();
86 }
87
88 [[nodiscard]] static constexpr auto columnDescriptor(std::size_t fieldIndex) -> const model::ColumnView&
89 {
90 return detail::columnForField<std::remove_cv_t<T>, SchemaType>(fieldIndex);
91 }
92};
93} // namespace orm::db::binding
94namespace orm::db::binding
95{
97{
98 auto operator()(const PrimaryKey& left, const PrimaryKey& right) const -> bool
99 {
100 return std::lexicographical_compare(left.begin(), left.end(), right.begin(), right.end(),
101 [](const auto& lhs, const auto& rhs) { return (lhs <=> rhs) < 0; });
102 }
103};
104
106{
107 return value;
108}
109
110template <typename T>
111struct IsOptional : std::false_type
112{
113};
114
115template <typename T>
116struct IsOptional<std::optional<T>> : std::true_type
117{
118};
119
120template <typename T>
121inline constexpr bool isOptional = IsOptional<std::remove_cv_t<T>>::value;
122
123template <typename T>
124auto toPrimaryKeyValue(const T& value, const std::string& fieldName) -> query::QueryValue
125{
126 using value_t = std::remove_cv_t<T>;
127
128 if constexpr (model::isNullable<value_t>)
129 {
131 {
132 throw std::invalid_argument{"Primary-key field must not be NULL: " + fieldName};
133 }
134
135 return toPrimaryKeyValue(NullableAdapter<value_t>::value(value), fieldName);
136 }
137 else if constexpr (ValueConvertible<value_t>)
138 {
139 try
140 {
142 }
143 catch (const std::invalid_argument&)
144 {
145 throw ConversionError{"A primary-key value was rejected by its converter"};
146 }
147 }
148 else if constexpr (requires { query::QueryValue{value}; })
149 {
150 if constexpr (UuidAdaptable<value_t>)
151 return query::QueryValue{canonicalUuid(value)};
152 else if constexpr (SociEncodedValue<value_t>)
153 (void)encodeScalarValue(value);
154 return query::QueryValue{value};
155 }
156 else
157 {
158 throw std::invalid_argument{"Unsupported primary-key field type: " + fieldName};
159 }
160}
161
162template <typename SchemaType, typename T>
163auto getPrimaryKey(const T& object) -> PrimaryKey
164{
165 static_assert(SchemaType::template contains<std::remove_cv_t<T>>,
166 "A primary key can be read only from a model in the selected Schema");
167 constexpr auto descriptor = model::modelView<SchemaType, std::remove_cv_t<T>>();
168 const auto objectAsTuple = reflection::fieldPointers(object);
169 PrimaryKey key;
170 key.reserve(descriptor->primaryKeyIndices.size());
171
172 auto appendPrimaryKeyField = [&key]<typename Index>(Index, const auto* field)
173 {
174 using field_t = std::decay_t<decltype(*field)>;
175
177 {
178 return;
179 }
180 else
181 {
182 constexpr auto* column = detail::mappedColumn<std::remove_cv_t<T>, SchemaType, Index::value>;
183 if constexpr (column != nullptr)
184 {
185 if (column->isPrimaryKey)
186 {
187 key.push_back(toPrimaryKeyValue(*field, std::string{column->fieldName}));
188 }
189 }
190 }
191 };
192
193 utils::constexpr_for_tuple(objectAsTuple, appendPrimaryKeyField);
194
195 if (key.empty())
196 {
197 throw std::invalid_argument{"Relation endpoint must define a non-empty primary key"};
198 }
199
200 return key;
201}
202
203inline auto getPrimaryKeyValue(const auto& values, const std::string& name, model::ColumnType type) -> query::QueryValue
204{
205 if (values.get_indicator(name) == soci::i_null)
206 {
207 throw ConversionError{"Cannot hydrate NULL relation primary key: " + name};
208 }
209
210 const auto fromStorage = [type, &name](query::QueryValue::Value value)
211 {
212 try
213 {
214 return query::QueryValue::fromStorage(type, std::move(value));
215 }
216 catch (const std::invalid_argument&)
217 {
218 throw ConversionError{"Cannot hydrate relation primary key without data loss: " + name};
219 }
220 };
221
222 switch (type)
223 {
230 return fromStorage(getNumericValue<int>(values, name));
233 return fromStorage(getNumericValue<unsigned long long>(values, name));
235 return fromStorage(getNumericValue<long long>(values, name));
238 return fromStorage(getNumericValue<double>(values, name));
240 return fromStorage(values.template get<std::string>(name));
242 return fromStorage(getEncodedScalarValue<Date>(values, name));
244 return fromStorage(getEncodedScalarValue<TimeOfDay>(values, name));
246 return fromStorage(getEncodedScalarValue<LocalDateTime>(values, name));
248 return fromStorage(getEncodedScalarValue<UtcTimestamp>(values, name));
250 return fromStorage(getEncodedScalarValue<Uuid>(values, name));
251 }
252
253 throw std::invalid_argument{"Unsupported relation primary-key column: " + name};
254}
255
256inline auto getPrimaryKeyColumns(const model::ModelView& model) -> std::vector<const model::ColumnView*>
257{
258 std::vector<const model::ColumnView*> columns;
259 columns.reserve(model->primaryKeyIndices.size());
260
261 for (const auto columnIndex : model->primaryKeyIndices)
262 {
263 if (columnIndex >= model->columns.size())
264 {
265 throw std::invalid_argument{"Primary-key descriptor points outside the model columns"};
266 }
267
268 const auto& column = model->columns[columnIndex];
269 if (column.kind != model::FieldKind::Scalar)
270 {
271 throw std::invalid_argument{"Relations with model-valued primary-key fields are not supported"};
272 }
273 columns.push_back(&column);
274 }
275
276 if (columns.empty())
277 {
278 throw std::invalid_argument{"Relation endpoint must define a non-empty primary key"};
279 }
280
281 return columns;
282}
283
284inline auto relationOwnerAlias(const model::ColumnView& column) -> std::string
285{
286 return std::format("__orm_owner_{}", column.name);
287}
288} // 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
A value that can be bound as a query parameter.
Definition value.cppm:33
std::variant< int, long long, unsigned long long, double, std::string, Date, TimeOfDay, LocalDateTime, UtcTimestamp, Uuid > Value
Definition value.cppm:35
static auto fromStorage(model::ColumnType logicalType, Value value) -> QueryValue
Restores a canonical transport value with its model-level type.
Definition value.cppm:115
auto getPrimaryKeyColumns(const model::ModelView &model) -> std::vector< const model::ColumnView * >
Definition payload.cppm:256
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 getPrimaryKey(const T &object) -> PrimaryKey
Definition payload.cppm:163
auto getNumericValue(const auto &values, const std::string &fieldName) -> Result
Definition numeric.cppm:421
std::vector< query::QueryValue > PrimaryKey
auto canonicalUuid(const T &value) -> Uuid
Definition numeric.cppm:93
auto relationOwnerAlias(const model::ColumnView &column) -> std::string
Definition payload.cppm:284
auto getPrimaryKeyValue(const auto &values, const std::string &name, model::ColumnType type) -> query::QueryValue
Definition payload.cppm:203
constexpr bool isOptional
Definition payload.cppm:121
auto toPrimaryKeyValue(const T &value, const std::string &fieldName) -> query::QueryValue
Definition payload.cppm:124
auto toQueryValue(const query::QueryValue &value) -> query::QueryValue
Definition payload.cppm:105
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 constexpr auto modelDescriptor() noexcept -> model::ModelView
Definition payload.cppm:77
static constexpr auto columnDescriptor() noexcept -> const model::ColumnView &
Definition payload.cppm:83
static constexpr auto columnDescriptor(std::size_t fieldIndex) -> const model::ColumnView &
Definition payload.cppm:88
auto operator()(const PrimaryKey &left, const PrimaryKey &right) const -> bool
Definition payload.cppm:98
Trivially-copyable handle to one model in immutable Schema storage.
Definition views.cppm:181