diff --git a/hdr/sqlite_modern_cpp/extensions/null_support.h b/hdr/sqlite_modern_cpp/extensions/null_support.h new file mode 100644 index 00000000..01a8db9f --- /dev/null +++ b/hdr/sqlite_modern_cpp/extensions/null_support.h @@ -0,0 +1,33 @@ +#pragma once + +using namespace sqlite; +using namespace std; + +namespace sqlite { + // custom null value + struct null_value { + bool value = true; + void operator=(bool val) { value = val; } + operator bool() const { return value; } + }; + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" + template<> inline database_binder::chain_type& operator <<(database_binder::chain_type& db, const sqlite::null_value& val) { + int hresult; + if((hresult = sqlite3_bind_null(db->_stmt.get(), db->_inx)) != SQLITE_OK) { + exceptions::throw_sqlite_error(hresult); + } + ++db->_inx; + return db; + } +#pragma GCC diagnostic pop + + template<> inline void get_col_from_db(database_binder& db, int inx, sqlite::null_value& d) { + if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { + d = true; + } else { + d = false; + } + } +} \ No newline at end of file diff --git a/tests/null_value.cc b/tests/null_value.cc new file mode 100644 index 00000000..e2a928db --- /dev/null +++ b/tests/null_value.cc @@ -0,0 +1,35 @@ +#include +#include +#include +#include + +int main() { + + try { + database db(":memory:"); + db << "CREATE TABLE tbl (id integer, name string);"; + db << "INSERT INTO tbl VALUES (?, ?);" << 1 << "hello"; + db << "INSERT INTO tbl VALUES (?, ?);" << 2 << null_value(); + + db << "select id,name from tbl where id = 1" >> [](int id, null_value name_null) { + cout << "Name should not be null for ID:" << id; + if(name_null) exit(EXIT_FAILURE); + }; + + db << "select id,name from tbl where id = 2" >> [](int id, null_value name_null) { + cout << "Name should be null for ID:" << id; + if(!name_null) exit(EXIT_FAILURE); + }; + + + } catch(sqlite_exception e) { + cout << "Sqlite error " << e.what() << endl; + exit(EXIT_FAILURE); + } catch(...) { + cout << "Unknown error\n"; + exit(EXIT_FAILURE); + } + + cout << "OK\n"; + exit(EXIT_SUCCESS); +}