Skip to content

Commit 6447e50

Browse files
Merge pull request #411 from LASTRADA-Software/improvement/const_correctness
Allow use entity as a const reference when loading belongs to fields
2 parents 7096807 + f790c3b commit 6447e50

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/Lightweight/DataMapper/BelongsTo.hpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ class BelongsTo
324324
}
325325

326326
private:
327-
void RequireLoaded()
327+
void RequireLoaded() const
328328
{
329329
if (_loaded)
330330
return;
@@ -346,9 +346,9 @@ class BelongsTo
346346

347347
ValueType _referencedFieldValue {};
348348
Loader _loader {};
349-
bool _loaded = false;
350349
bool _modified = false;
351-
std::unique_ptr<ReferencedRecord> _record {};
350+
mutable bool _loaded = false;
351+
mutable std::unique_ptr<ReferencedRecord> _record {};
352352
};
353353

354354
template <auto ReferencedField, auto ColumnNameOverrideString, SqlNullable Nullable>

src/tests/DataMapper/RelationTests.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,4 +620,30 @@ TEST_CASE_METHOD(SqlTestFixture, "BelongsTo Optinal records", "[DataMapper]")
620620
REQUIRE(!nullableFKUserNotSet.user.Record().transform(Light::Unwrap).value_or(User{}).id.Value());
621621
}
622622

623+
bool CheckFieldInEntityConstCorrectness(auto const& nullableFKUser)
624+
{
625+
return static_cast<bool>(nullableFKUser.id.Value());
626+
}
627+
628+
bool CheckBelongsToInEntityConstCorrectness(auto const& nullableFKUser)
629+
{
630+
return nullableFKUser.user.Record().transform(Light::Unwrap).has_value();
631+
}
632+
633+
TEST_CASE_METHOD(SqlTestFixture, "Entity const corectness", "[DataMapper]")
634+
{
635+
auto dm = DataMapper();
636+
637+
dm.CreateTables<User, NullableForeignKeyUser>();
638+
639+
auto user = User { .id = SqlGuid::Create(), .name = "John Doe" };
640+
dm.Create(user);
641+
642+
auto nullableFKUser = NullableForeignKeyUser { .user = user };
643+
dm.Create(nullableFKUser);
644+
645+
REQUIRE(CheckFieldInEntityConstCorrectness(nullableFKUser));
646+
REQUIRE(CheckBelongsToInEntityConstCorrectness(nullableFKUser));
647+
}
648+
623649
// NOLINTEND(bugprone-unchecked-optional-access)

0 commit comments

Comments
 (0)