Skip to content

Commit f53139f

Browse files
jkaliasclaude
andauthored
Make Database mutators non-const and Instance() return a writable handle (#26) (#36)
Instance() returned std::shared_ptr<const Database>, yet Save, SaveAutoIncrement, Update, Delete, and UnsafeSql were all declared const - so a handle typed as pointer-to-const could freely mutate persistent state. It compiled because the connection is a raw sqlite3* (const does not propagate through the pointer) and db_mutex_ is mutable. The API misrepresented intent: const looked read-only but wasn't. Make const mean read-only: - Instance() now returns std::shared_ptr<Database>. - The write methods (Save/SaveAutoIncrement/Update/Delete overloads, UnsafeSql) and their private void* worker helpers are now non-const. - The genuine reads (FetchAll, Fetch, private FetchRecords) stay const, and db_mutex_ stays mutable so they can still lock it. The ownership/lifecycle model is unchanged: the alive-across-Finalize() guarantee comes from Instance() returning a strong shared_ptr, not from the pointee being const. Serialized access via db_mutex_, the retired_ reinitialization guard, and all CRUD semantics are untouched. A read-only view is still available via the implicit shared_ptr<Database> -> shared_ptr<const Database> conversion, through which only the const fetch methods compile; README updated accordingly. Existing call sites of the form `const auto db = Database::Instance()` still compile (const handle, non-const pointee). Tests: compile-time SFINAE checks in database_test.cc assert the new contract (Save is NOT invocable through const Database, FetchAll IS), with the trait machinery verified to detect the positive case on non-const Database so the negative assert isn't vacuous; plus a runtime test that a shared_ptr<const Database> view can still fetch. Full suite: 76/76 pass in both C++11 and C++20 (including the concurrency/lifecycle tests). Note this is an ABI change (method const-ness and Instance()'s return type alter mangled names) - acceptable for a source library. Claude-Session: https://claude.ai/code/session_01NUt3c1wdseRtRSSXfg3MCK Co-authored-by: Claude <noreply@anthropic.com>
1 parent c4cacba commit f53139f

4 files changed

Lines changed: 85 additions & 23 deletions

File tree

‎README.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ SQLite's serialized mode and all operations are serialized internally, so concur
180180
`Save`/`Fetch`/`Update`/`Delete` calls are safe (they execute one at a time rather than
181181
in parallel). `Initialize`, `Finalize`, and `Instance` are also safe to call concurrently.
182182

183-
**Ownership model.** `Instance()` returns a `std::shared_ptr<const Database>` rather than a
183+
**Ownership model.** `Instance()` returns a `std::shared_ptr<Database>` rather than a
184184
reference. Each user holds a strong handle, so the database stays alive for as long as anyone
185185
is using it: an operation in progress on one thread is never torn down by a concurrent
186186
`Finalize()` on another. `Finalize()` only drops the singleton's own handle; the connection is
@@ -197,6 +197,17 @@ std::thread worker([db] {
197197
worker.join();
198198
```
199199
200+
The write methods (`Save`, `SaveAutoIncrement`, `Update`, `Delete`, `UnsafeSql`) are
201+
non-`const`, and the fetch methods are `const`. To hand a component a read-only view, assign
202+
the handle to a `std::shared_ptr<const Database>` (the conversion is implicit) — through it,
203+
only the fetch methods compile:
204+
205+
```c++
206+
std::shared_ptr<const Database> reader = Database::Instance();
207+
auto people = reader->FetchAll<Person>(); // ok
208+
// reader->Save(person); // does not compile: Save is not const
209+
```
210+
200211
Writes (and reads) are serialized, so they are safe but not concurrent; true write parallelism
201212
is tracked as future work.
202213

‎include/database.h‎

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,10 @@ class REFLECTION_EXPORT Database {
5353

5454
/// Retrieves the database singleton wrapper for further operations. The returned shared
5555
/// handle keeps the database alive for as long as the caller holds it, so an operation in
56-
/// progress is never torn down by a concurrent Finalize().
57-
static std::shared_ptr<const Database> Instance();
56+
/// progress is never torn down by a concurrent Finalize(). The handle is writable; for a
57+
/// read-only view, assign it to a std::shared_ptr<const Database> (the conversion is
58+
/// implicit), through which only the const fetch methods are callable.
59+
static std::shared_ptr<Database> Instance();
5860

5961
~Database();
6062

@@ -99,7 +101,7 @@ class REFLECTION_EXPORT Database {
99101
/// Saves a given record in the database.
100102
/// This corresponds to an INSERT query in the SQL syntax
101103
template <typename T>
102-
void Save(const T& model) const {
104+
void Save(const T& model) {
103105
const auto type_id = typeid(T).name();
104106
const auto& record = GetRecord(type_id);
105107
Save((void*)&model, record);
@@ -109,7 +111,7 @@ class REFLECTION_EXPORT Database {
109111
/// The newly generated id is written back into the passed-in model.
110112
/// This corresponds to an INSERT query in the SQL syntax
111113
template <typename T>
112-
void SaveAutoIncrement(T& model) const {
114+
void SaveAutoIncrement(T& model) {
113115
const auto type_id = typeid(T).name();
114116
const auto& record = GetRecord(type_id);
115117
model.id = SaveAutoIncrement((void*)&model, record);
@@ -118,7 +120,7 @@ class REFLECTION_EXPORT Database {
118120
/// Saves multiple records iteratively in the database.
119121
/// This corresponds to an INSERT query in the SQL syntax
120122
template <typename T>
121-
void Save(const std::vector<T>& models) const {
123+
void Save(const std::vector<T>& models) {
122124
const auto type_id = typeid(T).name();
123125
const auto& record = GetRecord(type_id);
124126
for (const auto& model : models) {
@@ -130,7 +132,7 @@ class REFLECTION_EXPORT Database {
130132
/// The newly generated ids are written back into the passed-in models.
131133
/// This corresponds to an INSERT query in the SQL syntax
132134
template <typename T>
133-
void SaveAutoIncrement(std::vector<T>& models) const {
135+
void SaveAutoIncrement(std::vector<T>& models) {
134136
const auto type_id = typeid(T).name();
135137
const auto& record = GetRecord(type_id);
136138
for (auto& model : models) {
@@ -141,7 +143,7 @@ class REFLECTION_EXPORT Database {
141143
/// Updates a given record in the database.
142144
/// This corresponds to an UPDATE query in the SQL syntax
143145
template <typename T>
144-
void Update(const T& model) const {
146+
void Update(const T& model) {
145147
const auto type_id = typeid(T).name();
146148
const auto& record = GetRecord(type_id);
147149
Update((void*)&model, record);
@@ -150,7 +152,7 @@ class REFLECTION_EXPORT Database {
150152
/// Updates multiple records iteratively in the database.
151153
/// This corresponds to an UPDATE query in the SQL syntax
152154
template <typename T>
153-
void Update(const std::vector<T>& models) const {
155+
void Update(const std::vector<T>& models) {
154156
const auto type_id = typeid(T).name();
155157
const auto& record = GetRecord(type_id);
156158
for (const auto& model : models) {
@@ -161,7 +163,7 @@ class REFLECTION_EXPORT Database {
161163
/// Deletes a given record from the database.
162164
/// This corresponds to an DELETE query in the SQL syntax
163165
template <typename T>
164-
void Delete(const T& model) const {
166+
void Delete(const T& model) {
165167
const auto type_id = typeid(T).name();
166168
const auto& record = GetRecord(type_id);
167169
const auto equal_id_predicate = Equal(&T::id, model.id);
@@ -171,7 +173,7 @@ class REFLECTION_EXPORT Database {
171173
/// Deletes a given record from the database, which matches a given id.
172174
/// This corresponds to an DELETE query in the SQL syntax
173175
template <typename T>
174-
void Delete(int64_t id) const {
176+
void Delete(int64_t id) {
175177
const auto type_id = typeid(T).name();
176178
const auto& record = GetRecord(type_id);
177179
const auto equal_id_predicate = Equal(&T::id, id);
@@ -181,15 +183,15 @@ class REFLECTION_EXPORT Database {
181183
/// Deletes multiple records of a given type from the database, which match a given predicate.
182184
/// This corresponds to an DELETE query in the SQL syntax, with an additional WHERE clause
183185
template <typename T>
184-
void Delete(const QueryPredicateBase* predicate) const {
186+
void Delete(const QueryPredicateBase* predicate) {
185187
const auto type_id = typeid(T).name();
186188
const auto& record = GetRecord(type_id);
187189
Delete(record, predicate);
188190
}
189191

190192
/// Executes a raw SQL query. A trailing semicolon is added if needed.
191193
/// Prefer the type-safe CRUD APIs for user-provided values.
192-
void UnsafeSql(const std::string& raw_sql_query) const;
194+
void UnsafeSql(const std::string& raw_sql_query);
193195

194196
private:
195197
explicit Database(const char* path);
@@ -214,17 +216,17 @@ class REFLECTION_EXPORT Database {
214216
}
215217

216218
/// Saves a single record in the database
217-
void Save(void* p, const Reflection& record) const;
219+
void Save(void* p, const Reflection& record);
218220

219221
/// Saves a single record in the database, letting SQLite assign its id,
220222
/// and returns the id that was generated for the inserted row
221-
int64_t SaveAutoIncrement(void* p, const Reflection& record) const;
223+
int64_t SaveAutoIncrement(void* p, const Reflection& record);
222224

223225
/// Updates a single record in the database
224-
void Update(void* p, const Reflection& record) const;
226+
void Update(void* p, const Reflection& record);
225227

226228
/// Deletes a single record from the database
227-
void Delete(const Reflection& record, const QueryPredicateBase* predicate) const;
229+
void Delete(const Reflection& record, const QueryPredicateBase* predicate);
228230

229231
static std::shared_ptr<Database> instance_;
230232

‎src/database.cc‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ Database::Database(const char* path) : db_(nullptr) {
105105
}
106106
}
107107

108-
std::shared_ptr<const Database> Database::Instance() {
108+
std::shared_ptr<Database> Database::Instance() {
109109
std::lock_guard<std::mutex> lock(instance_mutex_);
110110
if (instance_ == nullptr) {
111111
throw std::runtime_error("Database has not been initialized; call Database::Initialize() first");
@@ -117,13 +117,13 @@ const Reflection& Database::GetRecord(const std::string& type_id) {
117117
return GetReflectionRegister().records.at(type_id);
118118
}
119119

120-
void Database::Save(void* p, const Reflection& record) const {
120+
void Database::Save(void* p, const Reflection& record) {
121121
std::lock_guard<std::mutex> lock(db_mutex_);
122122
InsertQuery query(db_, record, p);
123123
query.Execute();
124124
}
125125

126-
int64_t Database::SaveAutoIncrement(void* p, const Reflection& record) const {
126+
int64_t Database::SaveAutoIncrement(void* p, const Reflection& record) {
127127
// The lock spans both the insert and the rowid read so that, on the shared connection,
128128
// sqlite3_last_insert_rowid() reflects this insert and not one from another thread.
129129
std::lock_guard<std::mutex> lock(db_mutex_);
@@ -132,19 +132,19 @@ int64_t Database::SaveAutoIncrement(void* p, const Reflection& record) const {
132132
return sqlite3_last_insert_rowid(db_);
133133
}
134134

135-
void Database::Update(void* p, const Reflection& record) const {
135+
void Database::Update(void* p, const Reflection& record) {
136136
std::lock_guard<std::mutex> lock(db_mutex_);
137137
UpdateQuery query(db_, record, p);
138138
query.Execute();
139139
}
140140

141-
void Database::Delete(const Reflection& record, const QueryPredicateBase* predicate) const {
141+
void Database::Delete(const Reflection& record, const QueryPredicateBase* predicate) {
142142
std::lock_guard<std::mutex> lock(db_mutex_);
143143
DeleteQuery query(db_, record, predicate);
144144
query.Execute();
145145
}
146146

147-
void Database::UnsafeSql(const std::string& raw_sql_query) const {
147+
void Database::UnsafeSql(const std::string& raw_sql_query) {
148148
std::lock_guard<std::mutex> lock(db_mutex_);
149149
SqlQuery sql(db_, raw_sql_query);
150150
sql.Execute();

‎tests/database_test.cc‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,49 @@
2424

2525
#include <gtest/gtest.h>
2626

27+
#include <memory>
28+
#include <type_traits>
29+
#include <utility>
30+
2731
#include "company.h"
2832
#include "id_only_record.h"
2933
#include "person.h"
3034
#include "pet.h"
3135

3236
using namespace sqlite_reflection;
3337

38+
namespace {
39+
// C++11 stand-in for std::void_t (C++17)
40+
template <typename...>
41+
struct MakeVoid {
42+
typedef void type;
43+
};
44+
45+
// Detects whether Save(const T&) is invocable through a const Database
46+
template <typename T, typename = void>
47+
struct CanSaveThroughConst : std::false_type {};
48+
49+
template <typename T>
50+
struct CanSaveThroughConst<
51+
T, typename MakeVoid<decltype(std::declval<const Database&>().Save(std::declval<const T&>()))>::type>
52+
: std::true_type {};
53+
54+
// Detects whether FetchAll<T>() is invocable through a const Database
55+
template <typename T, typename = void>
56+
struct CanFetchAllThroughConst : std::false_type {};
57+
58+
template <typename T>
59+
struct CanFetchAllThroughConst<T, typename MakeVoid<decltype(std::declval<const Database&>().FetchAll<T>())>::type>
60+
: std::true_type {};
61+
} // namespace
62+
63+
// The const-correctness contract (#26): const means read-only. A handle to a const Database
64+
// can fetch but not mutate; the write methods are only invocable through a non-const handle.
65+
static_assert(!CanSaveThroughConst<Person>::value,
66+
"Save must not be invocable through a const Database - write methods are non-const");
67+
static_assert(CanFetchAllThroughConst<Person>::value,
68+
"FetchAll must remain invocable through a const Database - read methods are const");
69+
3470
class DatabaseTest : public ::testing::Test {
3571
void SetUp() override {
3672
Database::Initialize("");
@@ -41,6 +77,19 @@ class DatabaseTest : public ::testing::Test {
4177
}
4278
};
4379

80+
TEST_F(DatabaseTest, ReadOnlyHandleCanStillFetch) {
81+
const auto db = Database::Instance();
82+
const Person p{L"ada", L"lovelace", 36, true, 1};
83+
db->Save(p);
84+
85+
// The implicit shared_ptr<Database> -> shared_ptr<const Database> conversion yields a
86+
// read-only view, through which the const fetch methods keep working
87+
std::shared_ptr<const Database> reader = Database::Instance();
88+
const auto all = reader->FetchAll<Person>();
89+
ASSERT_EQ(1, all.size());
90+
EXPECT_EQ(p.first_name, all[0].first_name);
91+
}
92+
4493
TEST_F(DatabaseTest, Initialization) {
4594
const auto db = Database::Instance();
4695

0 commit comments

Comments
 (0)