Skip to content

Commit c35dc2a

Browse files
jkaliasclaude
andauthored
Adopt fcpp::vector in the public Database API (#39)
* Return fcpp::vector from the public Database query API FetchAll, Fetch(predicate) and the private FetchRecords hydration loop now return fcpp::vector<T> instead of std::vector<T>, so callers can chain functional operations (filter/map/all_of/...) directly on a query result. The hydration loop builds the result with insert_back(std::move(model)), keeping the no-extra-copy fetch path. The batch Save/SaveAutoIncrement/Update methods now take fcpp::vector<T>, with thin std::vector overloads kept for source compatibility: they copy into an fcpp::vector and forward, and the SaveAutoIncrement wrapper writes the generated ids back into the caller's std::vector. Internal plumbing (bindings, query classes, reflection metadata) stays on std::vector; only the public template API changes. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YLXHcZjrnrdhRZAgqDh6kd * Add tests for fcpp::vector query results and batch overloads Covers the point of the migration: chaining filter + map and all_of/any_of directly on a fetch result, range-for/indexing parity with std::vector, and that batch Save/Update/SaveAutoIncrement accept an fcpp::vector with ids written back. Also verifies the std::vector compatibility overloads still work, including id write-back through the SaveAutoIncrement wrapper. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YLXHcZjrnrdhRZAgqDh6kd * Document fcpp::vector query results in the README Adds a "Working with query results" section showing a filter/map chain, notes that batch writes accept an fcpp::vector, and adds a migration note: auto call sites are unaffected, explicit std::vector bindings need iterator construction, and indexing is bounds-checked (aborts instead of UB). Updates the one example that bound a fetch result to std::vector, and lists functional_cpp as a dependency. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YLXHcZjrnrdhRZAgqDh6kd * Preserve per-row ids in the SaveAutoIncrement std::vector overload The std::vector compatibility wrapper copied into an fcpp::vector, ran the whole batch, then copied ids back at the end. Because each insert commits independently, a later row throwing would skip the end copy-back and leave the caller's std::vector without ids for rows that already committed. Save each record through the single-record overload instead, writing every id back as soon as its row is inserted - restoring the pre-fcpp::vector partial-success behavior and dropping the container copy. Addresses a Codex review comment on PR #39. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YLXHcZjrnrdhRZAgqDh6kd --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent cea5f9f commit c35dc2a

3 files changed

Lines changed: 239 additions & 11 deletions

File tree

‎README.md‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ A C++ wrapper for SQLite that provides compile-time checked CRUD operations for
1313
- [Opening and closing the database](#opening-and-closing-the-database)
1414
- [Saving records](#saving-records)
1515
- [Fetching records](#fetching-records)
16+
- [Working with query results](#working-with-query-results)
1617
- [Updating records](#updating-records)
1718
- [Deleting records](#deleting-records)
1819
- [Date and time fields](#date-and-time-fields)
@@ -346,6 +347,38 @@ Available predicate helpers include:
346347

347348
Predicate values are bound with SQLite prepared statements. Text payloads are treated as values, not SQL syntax.
348349

350+
## Working with query results
351+
352+
`FetchAll` and `Fetch` return an [`fcpp::vector<T>`](https://github.com/jkalias/functional_cpp)
353+
rather than a `std::vector<T>`, so functional operations can be chained directly on the result
354+
without wrapping it yourself:
355+
356+
```c++
357+
// Full names of every adult, straight off the query result.
358+
const auto adult_names = db->FetchAll<Person>()
359+
.filter([](const Person& p) { return p.age >= 18; })
360+
.map<std::wstring>([](const Person& p) { return p.GetFullName(); });
361+
362+
// Predicate-style checks are available too.
363+
const bool everyone_is_adult = db->FetchAll<Person>()
364+
.all_of([](const Person& p) { return p.age >= 18; });
365+
```
366+
367+
`fcpp::vector` also supports `map`, `all_of`/`any_of`/`none_of`, `sort`, `distinct`, `zip`, and lazy
368+
pipelines via `.lazy()`; see the [functional_cpp](https://github.com/jkalias/functional_cpp)
369+
documentation. The batch `Save`, `SaveAutoIncrement`, and `Update` overloads accept an
370+
`fcpp::vector<T>` as well.
371+
372+
**Migration note.** Because the result type changed from `std::vector<T>` to `fcpp::vector<T>`:
373+
374+
- `auto` call sites, range-`for` loops, indexing (`result[i]`), and `size()` are unaffected.
375+
- Code that binds a result to a `std::vector<T>` explicitly no longer compiles, because there is no
376+
implicit conversion back. Iterate the result directly, keep it as `fcpp::vector` (or `auto`), or
377+
construct a `std::vector` from its iterators: `std::vector<Person>(result.begin(), result.end())`.
378+
- Indexing is **always bounds-checked**, in release builds too: `result[i]` for an out-of-range `i`
379+
calls `std::abort()` instead of being undefined behavior (unless the library is built with
380+
`FCPP_NO_PRECONDITION_CHECKS`).
381+
349382
## Updating records
350383
351384
Fetch or construct a record, change its fields, and pass it to `Update`. The `id` identifies the row to update.
@@ -363,7 +396,7 @@ Multiple records can be updated in one call:
363396

364397
```c++
365398
// Update each record in the vector by its id.
366-
std::vector<Person> people = db->FetchAll<Person>();
399+
auto people = db->FetchAll<Person>(); // fcpp::vector<Person>
367400
people[0].last_name = L"Rambo";
368401
people[1].age = 20;
369402

@@ -494,6 +527,8 @@ You can also open the generated `build/sqlite-cpp-reflection.sln` in Visual Stud
494527

495528
- CMake 3.14 or newer
496529
- A C++11-compatible compiler
530+
- [functional_cpp](https://github.com/jkalias/functional_cpp) for `fcpp::vector` (query results) and
531+
`fcpp::optional_t` (nullable fields), header-only, fetched by CMake
497532
- GoogleTest for tests, fetched by CMake
498533
- SQLite, vendored in `src/sqlite3.c` and `src/internal/sqlite3.h`
499534

‎include/database.h‎

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
#include "queries.h"
3333
#include "query_predicates.h"
3434
#include "reflection.h"
35+
#include "vector.h" // fcpp::vector, the functional container returned by the query API
3536

3637
struct sqlite3;
3738

@@ -66,19 +67,23 @@ class REFLECTION_EXPORT Database {
6667
Database& operator=(Database&&) = delete;
6768

6869
/// Retrieves all entries of a given record from the database.
69-
/// This corresponds to a SELECT query in the SQL syntax
70+
/// This corresponds to a SELECT query in the SQL syntax.
71+
/// The result is an fcpp::vector, so functional operations (filter/map/...) can be chained
72+
/// directly on it; range-for, indexing and size() work as with a std::vector.
7073
template <typename T>
71-
std::vector<T> FetchAll() const {
74+
fcpp::vector<T> FetchAll() const {
7275
const auto type_id = typeid(T).name();
7376
const auto& record = GetRecord(type_id);
7477
EmptyPredicate empty;
7578
return FetchRecords<T>(record, &empty);
7679
}
7780

7881
/// Retrieves all entries of a given record from the database, which match a given predicate.
79-
/// This corresponds to a SELECT query in the SQL syntax
82+
/// This corresponds to a SELECT query in the SQL syntax.
83+
/// The result is an fcpp::vector, so functional operations (filter/map/...) can be chained
84+
/// directly on it; range-for, indexing and size() work as with a std::vector.
8085
template <typename T>
81-
std::vector<T> Fetch(const QueryPredicateBase* predicate) const {
86+
fcpp::vector<T> Fetch(const QueryPredicateBase* predicate) const {
8287
const auto type_id = typeid(T).name();
8388
const auto& record = GetRecord(type_id);
8489
return FetchRecords<T>(record, predicate);
@@ -120,26 +125,43 @@ class REFLECTION_EXPORT Database {
120125
/// Saves multiple records iteratively in the database.
121126
/// This corresponds to an INSERT query in the SQL syntax
122127
template <typename T>
123-
void Save(const std::vector<T>& models) {
128+
void Save(const fcpp::vector<T>& models) {
124129
const auto type_id = typeid(T).name();
125130
const auto& record = GetRecord(type_id);
126131
for (const auto& model : models) {
127132
Save((void*)&model, record);
128133
}
129134
}
130135

136+
/// std::vector compatibility overload: copies into an fcpp::vector and forwards.
137+
template <typename T>
138+
void Save(const std::vector<T>& models) {
139+
Save(fcpp::vector<T>(models));
140+
}
141+
131142
/// Saves multiple records iteratively in the database, letting the database assign their ids.
132143
/// The newly generated ids are written back into the passed-in models.
133144
/// This corresponds to an INSERT query in the SQL syntax
134145
template <typename T>
135-
void SaveAutoIncrement(std::vector<T>& models) {
146+
void SaveAutoIncrement(fcpp::vector<T>& models) {
136147
const auto type_id = typeid(T).name();
137148
const auto& record = GetRecord(type_id);
138149
for (auto& model : models) {
139150
model.id = SaveAutoIncrement((void*)&model, record);
140151
}
141152
}
142153

154+
/// std::vector compatibility overload: saves each record through the single-record overload, so
155+
/// every generated id is written back into the caller's std::vector as soon as its row is
156+
/// inserted. This preserves the ids of already-committed rows if a later row in the batch fails
157+
/// (each insert commits independently), matching the pre-fcpp::vector behavior.
158+
template <typename T>
159+
void SaveAutoIncrement(std::vector<T>& models) {
160+
for (auto& model : models) {
161+
SaveAutoIncrement(model);
162+
}
163+
}
164+
143165
/// Updates a given record in the database.
144166
/// This corresponds to an UPDATE query in the SQL syntax
145167
template <typename T>
@@ -152,14 +174,20 @@ class REFLECTION_EXPORT Database {
152174
/// Updates multiple records iteratively in the database.
153175
/// This corresponds to an UPDATE query in the SQL syntax
154176
template <typename T>
155-
void Update(const std::vector<T>& models) {
177+
void Update(const fcpp::vector<T>& models) {
156178
const auto type_id = typeid(T).name();
157179
const auto& record = GetRecord(type_id);
158180
for (const auto& model : models) {
159181
Update((void*)&model, record);
160182
}
161183
}
162184

185+
/// std::vector compatibility overload: copies into an fcpp::vector and forwards.
186+
template <typename T>
187+
void Update(const std::vector<T>& models) {
188+
Update(fcpp::vector<T>(models));
189+
}
190+
163191
/// Deletes a given record from the database.
164192
/// This corresponds to an DELETE query in the SQL syntax
165193
template <typename T>
@@ -203,14 +231,14 @@ class REFLECTION_EXPORT Database {
203231
/// each matching row directly from the prepared statement into a newly constructed T -
204232
/// no intermediate string materialization of the result set
205233
template <typename T>
206-
std::vector<T> FetchRecords(const Reflection& record, const QueryPredicateBase* predicate) const {
234+
fcpp::vector<T> FetchRecords(const Reflection& record, const QueryPredicateBase* predicate) const {
207235
std::lock_guard<std::mutex> lock(db_mutex_);
208236
FetchRecordsQuery query(db_, record, predicate);
209-
std::vector<T> models;
237+
fcpp::vector<T> models;
210238
while (query.StepRow()) {
211239
T model;
212240
query.HydrateCurrentRow((void*)&model, record);
213-
models.emplace_back(std::move(model));
241+
models.insert_back(std::move(model));
214242
}
215243
return models;
216244
}

‎tests/functional_vector_test.cc‎

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
// MIT License
2+
//
3+
// Copyright (c) 2026 Ioannis Kaliakatsos
4+
//
5+
// Permission is hereby granted, free of charge, to any person obtaining a copy
6+
// of this software and associated documentation files (the "Software"), to deal
7+
// in the Software without restriction, including without limitation the rights
8+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
// copies of the Software, and to permit persons to whom the Software is
10+
// furnished to do so, subject to the following conditions:
11+
//
12+
// The above copyright notice and this permission notice shall be included in all
13+
// copies or substantial portions of the Software.
14+
//
15+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
// SOFTWARE.
22+
23+
#include <gtest/gtest.h>
24+
25+
#include <string>
26+
#include <vector>
27+
28+
#include "database.h"
29+
#include "person.h"
30+
#include "vector.h"
31+
32+
using namespace sqlite_reflection;
33+
34+
namespace {
35+
class FunctionalVectorTest : public ::testing::Test {
36+
void SetUp() override {
37+
Database::Initialize("");
38+
}
39+
40+
void TearDown() override {
41+
Database::Finalize();
42+
}
43+
};
44+
45+
// The whole point of the migration: a fetch result is an fcpp::vector, so functional operations
46+
// can be chained directly on it, without the caller wrapping the std::vector themselves.
47+
TEST_F(FunctionalVectorTest, FetchResultChainsFilterAndMap) {
48+
const auto db = Database::Instance();
49+
db->Save(std::vector<Person>{
50+
{L"ada", L"lovelace", 36, true, 1},
51+
{L"grace", L"hopper", 17, true, 2},
52+
{L"alan", L"turing", 41, true, 3},
53+
});
54+
55+
// filter() (mutating, returns vector&) then map<U>() (non-mutating) chained on the temporary
56+
// returned by FetchAll(), exactly as advertised in the README.
57+
const auto adult_names = db->FetchAll<Person>()
58+
.filter([](const Person& p) { return p.age >= 18; })
59+
.map<std::wstring>([](const Person& p) { return p.GetFullName(); });
60+
61+
ASSERT_EQ(2u, adult_names.size());
62+
EXPECT_EQ(L"ada lovelace", adult_names[0]);
63+
EXPECT_EQ(L"alan turing", adult_names[1]);
64+
}
65+
66+
TEST_F(FunctionalVectorTest, FetchResultSupportsAllOfAnyOf) {
67+
const auto db = Database::Instance();
68+
db->Save(std::vector<Person>{
69+
{L"ada", L"lovelace", 36, true, 1},
70+
{L"grace", L"hopper", 17, true, 2},
71+
});
72+
73+
const auto people = db->FetchAll<Person>();
74+
EXPECT_TRUE(people.all_of([](const Person& p) { return p.age > 0; }));
75+
EXPECT_FALSE(people.all_of([](const Person& p) { return p.age >= 18; }));
76+
EXPECT_TRUE(people.any_of([](const Person& p) { return p.age < 18; }));
77+
EXPECT_FALSE(people.any_of([](const Person& p) { return p.age > 100; }));
78+
}
79+
80+
// range-for and indexing over a fetch result keep working as with a std::vector
81+
TEST_F(FunctionalVectorTest, FetchResultSupportsRangeForAndIndexing) {
82+
const auto db = Database::Instance();
83+
db->Save(std::vector<Person>{
84+
{L"ada", L"lovelace", 36, true, 1},
85+
{L"alan", L"turing", 41, true, 2},
86+
});
87+
88+
const auto people = db->FetchAll<Person>();
89+
90+
int64_t total_age = 0;
91+
for (const auto& person : people) {
92+
total_age += person.age;
93+
}
94+
EXPECT_EQ(77, total_age);
95+
EXPECT_EQ(L"ada", people[0].first_name);
96+
EXPECT_EQ(L"alan", people[1].first_name);
97+
}
98+
99+
// Batch Save/Update accept an fcpp::vector directly.
100+
TEST_F(FunctionalVectorTest, BatchSaveAndUpdateAcceptFcppVector) {
101+
const auto db = Database::Instance();
102+
103+
fcpp::vector<Person> people;
104+
people.insert_back({L"ada", L"lovelace", 36, true, 1}).insert_back({L"alan", L"turing", 41, true, 2});
105+
106+
db->Save(people);
107+
108+
auto fetched = db->FetchAll<Person>();
109+
ASSERT_EQ(2u, fetched.size());
110+
EXPECT_EQ(36, fetched[0].age);
111+
112+
people[0].age = 37;
113+
db->Update(people);
114+
115+
fetched = db->FetchAll<Person>();
116+
ASSERT_EQ(2u, fetched.size());
117+
EXPECT_EQ(37, fetched[0].age);
118+
}
119+
120+
// SaveAutoIncrement writes the generated ids back into the passed-in fcpp::vector.
121+
TEST_F(FunctionalVectorTest, SaveAutoIncrementWritesIdsBackIntoFcppVector) {
122+
const auto db = Database::Instance();
123+
124+
fcpp::vector<Person> people;
125+
people.insert_back({L"ada", L"lovelace", 36, true}).insert_back({L"alan", L"turing", 41, true});
126+
127+
db->SaveAutoIncrement(people);
128+
129+
EXPECT_EQ(1, people[0].id);
130+
EXPECT_EQ(2, people[1].id);
131+
EXPECT_EQ(2u, db->FetchAll<Person>().size());
132+
}
133+
134+
// The std::vector compatibility overloads keep working for callers that still pass a std::vector.
135+
TEST_F(FunctionalVectorTest, StdVectorCompatibilityOverloadsStillWork) {
136+
const auto db = Database::Instance();
137+
138+
std::vector<Person> people;
139+
people.push_back({L"ada", L"lovelace", 36, true, 1});
140+
people.push_back({L"alan", L"turing", 41, true, 2});
141+
142+
db->Save(people);
143+
EXPECT_EQ(2u, db->FetchAll<Person>().size());
144+
145+
people[0].age = 37;
146+
db->Update(people);
147+
EXPECT_EQ(37, db->Fetch<Person>(1).age);
148+
}
149+
150+
// The SaveAutoIncrement std::vector wrapper writes the generated ids back into the caller's
151+
// std::vector, just like the fcpp::vector overload.
152+
TEST_F(FunctionalVectorTest, SaveAutoIncrementStdVectorWrapperWritesIdsBack) {
153+
const auto db = Database::Instance();
154+
155+
std::vector<Person> people;
156+
people.push_back({L"ada", L"lovelace", 36, true});
157+
people.push_back({L"alan", L"turing", 41, true});
158+
159+
db->SaveAutoIncrement(people);
160+
161+
EXPECT_EQ(1, people[0].id);
162+
EXPECT_EQ(2, people[1].id);
163+
EXPECT_EQ(2u, db->FetchAll<Person>().size());
164+
}
165+
} // namespace

0 commit comments

Comments
 (0)