Skip to content

Commit 9f861df

Browse files
Merge pull request #392 from LASTRADA-Software/feature/Delete_in_datamapper_query_builder
[DataMapper] Implement Delete query builder
2 parents f4d9da9 + 52c7677 commit 9f861df

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

src/Lightweight/DataMapper/DataMapper.hpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,21 @@ bool SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::Exist()
648648
return false;
649649
}
650650

651+
template <typename Record, typename Derived, DataMapperOptions QueryOptions>
652+
void SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::Delete()
653+
{
654+
auto stmt = SqlStatement { _dm.Connection() };
655+
656+
auto const query = _formatter.Delete(RecordTableName<Record>,
657+
this->_query.searchCondition.tableAlias,
658+
this->_query.searchCondition.tableJoins,
659+
this->_query.searchCondition.condition);
660+
661+
stmt.Prepare(query);
662+
stmt.Execute();
663+
stmt.CloseCursor();
664+
}
665+
651666
template <typename Record, typename Derived, DataMapperOptions QueryOptions>
652667
std::vector<Record> SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::All()
653668
{

src/Lightweight/DataMapper/QueryBuilders.hpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,9 @@ class [[nodiscard]] SqlCoreDataMapperQueryBuilder: public SqlBasicSelectQueryBui
6262
/// Executes a SELECT query and returns all records found.
6363
[[nodiscard]] std::vector<Record> All();
6464

65+
/// Executes a DELETE query.
66+
void Delete();
67+
6568
/// @brief Executes a SELECT query and returns all records found for the specified field.
6669
///
6770
/// @tparam Field The field to select from the record, in the form of &Record::FieldName.

src/tests/DataMapper/MiscTests.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,4 +520,26 @@ TEST_CASE_METHOD(SqlTestFixture, "SqlGuid", "[DataMapper]")
520520
}
521521
}
522522

523+
TEST_CASE_METHOD(SqlTestFixture, "Delete", "[DataMapper]")
524+
{
525+
auto dm = DataMapper::Create();
526+
527+
dm->CreateTable<Person>();
528+
for (auto const i: std::views::iota(0, 10))
529+
{
530+
dm->CreateExplicit(Person {
531+
.id = SqlGuid::Create(),
532+
.name = std::format("Person {}", i),
533+
.is_active = (i % 2) == 0,
534+
.age = i,
535+
});
536+
}
537+
CHECK(dm->Query<Person>().Count() == 10);
538+
dm->Query<Person>().Where(FieldNameOf<Member(Person::age)>, "<", 6).Delete();
539+
CHECK(dm->Query<Person>().Count() == 4);
540+
dm->Query<Person>().Delete();
541+
REQUIRE(dm->Query<Person>().Count() == 0);
542+
dm->Query<Person>().Delete();
543+
}
544+
523545
// NOLINTEND(bugprone-unchecked-optional-access)

0 commit comments

Comments
 (0)