I'm trying Object-Relational Mapping in C++ SOCI library with SQLite3 backend. But when I try to load from database REAL
value as C++'s double the std::bad_cast
is being thrown.
Full code:
#include <iostream>
#include <string>
#include <exception>
#include <soci/soci.h>
#include <soci/sqlite3/soci-sqlite3.h>
using namespace std;
using namespace soci;
struct Employee
{
int id;
std::string name;
double salary;
};
ostream& operator<<(ostream& o, const Employee& employee)
{
return o << "Employee(" << employee.id << "):" << employee.name << ", earns: " << employee.salary;
}
namespace soci
{
template<>
struct type_conversion<Employee>
{
typedef values base_type;
static void from_base(const values & v, indicator /* ind */, Employee & employee)
{
employee.id = v.get<int>("ID");
employee.name = v.get<std::string>("Name");
cout << "Type: " << v.get_properties("Salary").get_data_type() << endl; // the output is 0, so the type is soci::dt_string but not soci::dt_double
if (v.get_indicator("Salary") == i_ok)
employee.salary = v.get<double>("Salary");
}
static void to_base(const Employee& employee, values& v, indicator& ind)
{
v.set("ID", employee.id);
v.set("Name", employee.name);
v.set("Salary", employee.salary, employee.salary == 0. ? i_null : i_ok);
ind = i_ok;
}
};
}
int main()
{
try
{
soci::session sql(sqlite3, "employees.db");
sql << "CREATE TABLE IF NOT EXISTS Employees(" \
"ID INT PRIMARY KEY NOT NULL," \
"Name TEXT NOT NULL," \
"Salary REAL);";
sql << "INSERT INTO Employees (ID, Name, Salary) " \
"VALUES (1, 'Janusz Korwin-Mikke', 12000.01 ); ";
Employee employee = {};
sql << "SELECT * FROM Employees WHERE ID = 1;", into(employee);
cout << employee << endl;
}
catch (const exception &e)
{
cerr << "Error: " << e.what() << endl;
}
}
When I run the code I see the std::bad_cast
exception thrown in line:
employee.salary = v.get<double>("Salary");
despite the fact that in database it is REAL
type.
The code is working when I change the line into:
employee.salary = atof(v.get<std::string>("Salary").c_str());
I'm using SOCI-4.0.0 but the same problem was with previous version 3.2.3, I'm using SQLite3 on Windows 7 and MinGW compiler 7.3.0