Lightweight 0.20261105.1
Loading...
Searching...
No Matches
HasOneThrough.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5#include "../SqlStatement.hpp"
6#include "../Utils.hpp"
7#include "Error.hpp"
8#include "Record.hpp"
9
10#include <compare>
11#include <functional>
12#include <memory>
13#include <optional>
14#include <type_traits>
15
16namespace Lightweight
17{
18
19/// @brief Represents a one-to-one relationship through a join table.
20///
21/// The `OtherTable` parameter is the record reached through the join table.
22/// The `ThroughSpec` parameter is the join table, which references the current record. It is named
23/// with the @ref Through marker, so that the reader can tell it apart from the referenced record:
24///
25/// @code
26/// struct Account;
27/// struct AccountHistory;
28/// struct Supplier
29/// {
30/// Field<int, PrimaryKey::AutoAssign> id;
31/// HasOneThrough<AccountHistory, Through<Account>> accountHistory;
32/// };
33/// @endcode
34///
35/// Both foreign keys are located by matching the relationship *type*. When either record holds more
36/// than one foreign key into the same table, name the column to single one out - see
37/// the RelationSelector concept and the example on @ref HasManyThrough.
38///
39/// @tparam OtherTable The record type reached through the join table.
40/// @tparam ThroughSpec The join record, wrapped as `Through<T>`. Naming the record bare is deprecated.
41/// @tparam TheOwnerSelector Singles out the join record's foreign key pointing at the *owning* record.
42/// @tparam TheThroughSelector Singles out @p OtherTable's foreign key pointing at the join record.
43///
44/// @see DataMapper, Field, HasManyThrough, Through, RelationSelector
45/// @ingroup DataMapper
46template <typename OtherTable,
47 typename ThroughSpec,
48 auto TheOwnerSelector = AutoDetectRelation,
49 auto TheThroughSelector = AutoDetectRelation>
51{
53 "The selector template arguments of HasOneThrough must be foreign key column names "
54 "(a SqlRealName) or std::nullopt to resolve the relationship automatically.");
55
56 static_assert(!IsThrough<OtherTable>,
57 "The referenced record of HasOneThrough must not be wrapped in Through<>, "
58 "only the join record is.");
59
60 public:
61 /// The record type of the "through" side of the relationship.
63
64 /// The record type of the "Other" side of the relationship.
65 using ReferencedRecord = OtherTable;
66
67 /// Singles out the join record's foreign key pointing at the record owning this relationship.
68 static constexpr auto OwnerSelector = TheOwnerSelector;
69
70 /// Singles out @ref ReferencedRecord's foreign key pointing at @ref ThroughRecord.
71 static constexpr auto ThroughSelector = TheThroughSelector;
72
73 /// Emplaces the given record into this relationship.
74 LIGHTWEIGHT_FORCE_INLINE constexpr void EmplaceRecord(std::shared_ptr<ReferencedRecord> record)
75 {
76 _record = std::move(record);
77 _loadError.reset();
78 }
79
80 /// @brief Retrieves the record in this relationship, loading it on first access.
81 ///
82 /// Never throws for an unavailable record: the reason comes back as the error instead.
83 ///
84 /// @return The record; or @ref RelationError::NotFound when there is none,
85 /// @ref RelationError::NotConfigured when there is no loader (a hand-built record, or one read
86 /// with `loadRelations = false`), @ref RelationError::Outdated when the default connection
87 /// string changed since the record was read, @ref RelationError::QueryFailed when the load
88 /// query failed.
89 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE RelationResult<std::reference_wrapper<ReferencedRecord>> Record()
90 {
91 return Load().transform([this] { return std::reference_wrapper<ReferencedRecord> { *_record }; });
92 }
93
94 /// @copydoc Record()
95 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE RelationResult<std::reference_wrapper<ReferencedRecord const>> Record() const
96 {
97 return Load().transform([this] { return std::reference_wrapper<ReferencedRecord const> { *_record }; });
98 }
99
100 /// Checks if the record is loaded.
101 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE constexpr bool IsLoaded() const noexcept
102 {
103 return _record.get() != nullptr;
104 }
105
106 /// Unloads the record from memory, so the next access loads it again.
107 LIGHTWEIGHT_FORCE_INLINE void Unload() noexcept
108 {
109 _record.reset();
110 _loadError.reset();
111 }
112
113 /// @brief Retrieves the record in this relationship, loading it on first access.
114 /// @throws SqlRequireLoadedError The record is unavailable; @ref Record() reports why without throwing.
115 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE ReferencedRecord& operator*()
116 {
117 LoadOrThrow();
118 return *_record;
119 }
120
121 /// @copydoc operator*()
122 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE ReferencedRecord const& operator*() const
123 {
124 LoadOrThrow();
125 return *_record;
126 }
127
128 /// @brief Retrieves the record in this relationship, loading it on first access.
129 /// @throws SqlRequireLoadedError The record is unavailable; @ref Record() reports why without throwing.
130 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE ReferencedRecord* operator->()
131 {
132 LoadOrThrow();
133 return _record.get();
134 }
135
136 /// @copydoc operator->()
137 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE ReferencedRecord const* operator->() const
138 {
139 LoadOrThrow();
140 return _record.get();
141 }
142
143 /// Default three-way comparison operator.
144 std::weak_ordering operator<=>(HasOneThrough const& other) const noexcept = default;
145
146 /// Carries the deferred load, installed by the DataMapper.
147 struct Loader
148 {
149 /// Loads the referenced record: @ref RelationError::NotFound when there is none.
150 std::function<RelationResult<std::shared_ptr<ReferencedRecord>>()> loadReference {};
151 };
152
153 /// Used internally to configure on-demand loading of the record.
155 {
156 _loader = std::move(loader);
157 }
158
159 private:
160 /// Loads the record unless it already is, or its unavailability is already known.
161 ///
162 /// @ref RelationError::NotFound and @ref RelationError::Outdated are remembered until the record is
163 /// emplaced or unloaded; a failed query is retried on the next access.
164 [[nodiscard]] RelationResult<void> Load() const
165 {
166 if (IsLoaded())
167 return {};
168 if (_loadError)
169 return std::unexpected { *_loadError };
170 if (!_loader.loadReference)
171 return std::unexpected { RelationError::NotConfigured };
172
173 auto loaded = _loader.loadReference();
174 if (!loaded)
175 {
176 if (loaded.error() != RelationError::QueryFailed)
177 _loadError = loaded.error();
178 return std::unexpected { loaded.error() };
179 }
180 _record = std::move(*loaded);
181 return {};
182 }
183
184 void LoadOrThrow() const
185 {
186 if (auto const loaded = Load(); !loaded)
187 throw SqlRequireLoadedError(Reflection::TypeNameOf<std::remove_cvref_t<decltype(*this)>>, loaded.error());
188 }
189
190 Loader _loader {};
191
192 // We use shared_ptr to not require ReferencedRecord to be declared before HasOneThrough.
193 mutable std::shared_ptr<ReferencedRecord> _record {};
194 mutable std::optional<RelationError> _loadError {};
195};
196
197namespace detail
198{
199 template <typename T>
200 struct IsHasOneThrough: std::false_type
201 {
202 };
203
204 template <typename OtherTable, typename ThroughSpec, auto OwnerSelector, auto ThroughSelector>
205 struct IsHasOneThrough<HasOneThrough<OtherTable, ThroughSpec, OwnerSelector, ThroughSelector>>: std::true_type
206 {
207 };
208} // namespace detail
209
210template <typename T>
211constexpr bool IsHasOneThrough = detail::IsHasOneThrough<std::remove_cvref_t<T>>::value;
212
213} // namespace Lightweight
Represents a one-to-one relationship through a join table.
LIGHTWEIGHT_FORCE_INLINE void Unload() noexcept
Unloads the record from memory, so the next access loads it again.
void SetAutoLoader(Loader loader)
Used internally to configure on-demand loading of the record.
LIGHTWEIGHT_FORCE_INLINE constexpr bool IsLoaded() const noexcept
Checks if the record is loaded.
LIGHTWEIGHT_FORCE_INLINE ReferencedRecord * operator->()
Retrieves the record in this relationship, loading it on first access.
LIGHTWEIGHT_FORCE_INLINE constexpr void EmplaceRecord(std::shared_ptr< ReferencedRecord > record)
Emplaces the given record into this relationship.
static constexpr auto OwnerSelector
Singles out the join record's foreign key pointing at the record owning this relationship.
LIGHTWEIGHT_FORCE_INLINE ReferencedRecord & operator*()
Retrieves the record in this relationship, loading it on first access.
static constexpr auto ThroughSelector
Singles out ReferencedRecord's foreign key pointing at ThroughRecord.
LIGHTWEIGHT_FORCE_INLINE ReferencedRecord const * operator->() const
Retrieves the record in this relationship, loading it on first access.
std::weak_ordering operator<=>(HasOneThrough const &other) const noexcept=default
Default three-way comparison operator.
LIGHTWEIGHT_FORCE_INLINE RelationResult< std::reference_wrapper< ReferencedRecord > > Record()
Retrieves the record in this relationship, loading it on first access.
LIGHTWEIGHT_FORCE_INLINE RelationResult< std::reference_wrapper< ReferencedRecord const > > Record() const
Retrieves the record in this relationship, loading it on first access.
ThroughRecordOf< ThroughSpec > ThroughRecord
The record type of the "through" side of the relationship.
LIGHTWEIGHT_FORCE_INLINE ReferencedRecord const & operator*() const
Retrieves the record in this relationship, loading it on first access.
OtherTable ReferencedRecord
The record type of the "Other" side of the relationship.
Constrains what may be used to single out one of several foreign keys into the same table.
Definition Record.hpp:153
detail::ThroughRecordOfHelper< ThroughSpec >::type ThroughRecordOf
Resolves the join record of a through-relationship from its template argument.
Definition Record.hpp:250
std::expected< T, RelationError > RelationResult
The outcome of a relation access: the requested value, or why it is unavailable.
Definition Error.hpp:44
constexpr std::nullopt_t AutoDetectRelation
Selector value meaning "resolve the relationship automatically; the match must be unique".
Definition Record.hpp:138
Carries the deferred load, installed by the DataMapper.
std::function< RelationResult< std::shared_ptr< ReferencedRecord > >()> loadReference
Loads the referenced record: RelationError::NotFound when there is none.