Skip to content

Commit 6613f7c

Browse files
committed
Merge PR #173 from epsilon-phase into dev
2 parents 483ba78 + 07c9032 commit 6613f7c

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,7 @@ This does not happen if you use a `variant`.
370370
If the `variant` does an alternative of the same value type, an `mismatch` exception will be thrown.
371371
The value types are NULL, integer, real number, text and BLOB.
372372
To support all possible values, you can use `variant<nullptr_t, sqlite_int64, double, string, vector<char>`.
373+
It is also possible to use a variant with `std::monostate` in order to catch null values.
373374

374375
Errors
375376
----

hdr/sqlite_modern_cpp/type_wrapper.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,24 @@ namespace sqlite {
167167
sqlite3_result_null(db);
168168
}
169169

170+
#ifdef MODERN_SQLITE_STD_VARIANT_SUPPORT
171+
template<>
172+
struct has_sqlite_type<std::monostate, SQLITE_NULL, void> : std::true_type {};
173+
174+
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, std::monostate) {
175+
return sqlite3_bind_null(stmt, inx);
176+
}
177+
inline void store_result_in_db(sqlite3_context* db, std::monostate) {
178+
sqlite3_result_null(db);
179+
}
180+
inline std::monostate get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<std::monostate>) {
181+
return std::monostate();
182+
}
183+
inline std::monostate get_val_from_db(sqlite3_value *value, result_type<std::monostate>) {
184+
return std::monostate();
185+
}
186+
#endif
187+
170188
// str_ref
171189
template<>
172190
struct has_sqlite_type<std::string, SQLITE3_TEXT, void> : std::true_type {};

tests/variant.cc

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,29 @@ TEST_CASE("std::variant works", "[variant]") {
2929
db << "SELECT 0.0" >> v;
3030
REQUIRE(std::get<2>(v));
3131
}
32+
33+
TEST_CASE("std::monostate is a nullptr substitute", "[monostate]") {
34+
database db(":memory:");
35+
db << "CREATE TABLE foo (a);";
36+
37+
std::variant<std::monostate,std::string> v;
38+
v=std::monostate();
39+
db << "INSERT INTO foo VALUES (?)" << v;
40+
db << "INSERT INTO foo VALUES (?)" << "This isn't a monostate!";
41+
42+
bool found_null = false,
43+
found_string = false;
44+
45+
db << "SELECT * FROM foo"
46+
>> [&](std::variant<std::monostate, std::string> z) {
47+
if(z.index() == 0) {
48+
found_null = true;
49+
} else {
50+
found_string = true;
51+
}
52+
};
53+
REQUIRE((found_null && found_string));
54+
db << "SELECT NULL" >> v;
55+
REQUIRE(v.index() == 0);
56+
}
3257
#endif

0 commit comments

Comments
 (0)