Soci returning string datatype when averaging a column using sqlite3 backend
I've been wrestling with this for a couple of days and am about to
conclude that maybe SOCI with sqlite3 backend is a bad idea. When
averaging a column, SOCI is returning the result as a string instead of a
double. SOCI's conversion between sqlite3 data and c++ types seems
unpredicatable.
Is this normal behaviour for SOCI and I should just jump ship to a
different wrapper or am I doing something wrong?
Here's my test case:
#include <iostream>
#include <string>
#include <soci/soci.h>
#include <soci/soci-sqlite3.h>
#include <unistd.h>
using namespace soci;
const char* schema =
"CREATE TABLE IF NOT EXISTS test (\n"
" id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
" text TEXT NOT NULL,\n"
" number1 REAL NOT NULL,\n"
" number2 INTEGER NOT NULL\n"
");";
int main()
{
unlink("test.db");
session sql(sqlite3, "test.db");
sql << schema;
for (auto i = 0u; i < 10; ++i) {
sql << "insert into test (text, number1, number2) values(?, ?, ?)",
use(std::string{"this is text"}), use(i * 1.33), use(i);
}
for (auto& r : rowset<>(sql.prepare << "select text, number1, number2
from test")) {
assert(r.get_properties(0).get_data_type() == dt_string); // okay
assert(r.get_properties(1).get_data_type() == dt_double); // okay
assert(r.get_properties(2).get_data_type() == dt_integer); // okay
}
row r;
sql << "select avg(number1), avg(number2) from test", into(r);
assert(r.get_properties(0).get_data_type() != dt_string); // error
assert(r.get_properties(1).get_data_type() != dt_string); // error
assert(r.get_properties(0).get_data_type() == dt_double); // error
assert(r.get_properties(1).get_data_type() == dt_double); // error
std::cout << r.get<std::string>(0) << " "
<< r.get<std::string>(1) << std::endl; // desired output as
string: 5.985 4.5
std::cout << r.get<double>(0) << " "
<< r.get<double>(1) << std::endl; // std::bad_cast error
}
No comments:
Post a Comment