Skip to content

null support | header + test #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions hdr/sqlite_modern_cpp/extensions/null_support.h
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
35 changes: 35 additions & 0 deletions tests/null_value.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include <iostream>
#include <string>
#include <sqlite_modern_cpp.h>
#include <sqlite_modern_cpp/extensions/null_support.h>

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);
}