Pass-Through Version of TypeConversion
SOCI also provides a Row class and a ColumnProperties class, which you can use together as a means for selecting data from columns that are not known at compile time. For example, the code in Listing Seven selects data into a Row and creates an XML document from it.
#include "listing6.h" #include <soci.h> #include <boost/date_time/gregorian/gregorian.hpp> using namespace SOCI; using boost::gregorian::date; int main() { try { Session sql("oracle", "service=gen1 user=scott" " password=tiger"); sql << "create table person(id number, name varchar2(20)," " birthday date)"; int id = 100; std::string name("Bjarne"); date d(2001, boost::gregorian::Jan, 1); sql << "insert into person values(:id, :name, :bday)", use(id), use(name), use(d); Row r; sql << "select * from person", into(r); std::ostringstream doc; doc << "<ROW>" << std::endl; for(size_t i=0; i<r.size(); ++i) { const ColumnProperties& props = r.getProperties(i); doc << '<' << props.getName() << '>'; switch(props.getDataType()) { case eString: doc << r.get<std::string>(i); break; case eDouble: doc << r.get<double>(i); break; case eInteger: doc << r.get<int>(i); break; case eDate: doc << r.get<date>(i); break; default: throw std::runtime_error("unknown column type"); } doc << "</" << props.getName() << '>' << std::endl; } doc << "</ROW>"; std::cout<<doc.str()<<std::endl; sql << "drop table person"; } catch(std::exception& e) { std::cout<<e.what()<<std::endl; } }
First, the select statement is executed, passing an instance of Row by reference to the into() function. Then the Row's ColumnProperties are used to determine the name and data type of each column. The data for each column is retrieved from the Row by calling Row::get<T>(), where T is based on the data type of the column.
To enable Row::get<T>() to work with both custom types and native types, SOCI provides a default definition of TypeConversion<T>, where the base_type typedef is also T; see Listing Eight.
namespace SOCI { template<typename T> struct TypeConversion { typedef T base_type; static T from(T const &t) { return t; } // pass-through version of to() is not needed by SOCI }; };
The definition of Row::get<T>() calls TypeConversion<T>::from(). When you call Row::get<T>() where T is a type for which TypeConversion is specialized (such as boost::date::gregorian in the previous examples), the expected conversion takes place.
On the other hand, if you call Row::get<T>() where T is a type that is natively supported by SOCI (such as std::string or int), the compiler doesn't find a specialization of TypeConversioninstead it falls back to the nonspecialized definition, which simply acts as a pass through.