Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

Supporting Custom C++ Types


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.

Listing Seven
#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.

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 TypeConversion—instead it falls back to the nonspecialized definition, which simply acts as a pass through.

Aggregate Types and Object-Relational Mapping

The potential custom types I have discussed so far all map directly to fundamental database types. For example, no matter what your preferred String class is, you would add support for it by defining a TypeConversion<> specialization using the base_type std::string. SOCI in turn uses it to read/write to a single character-based column in the database.

In fact, you can also provide a specialization of the TypeConversion traits class to support custom aggregate types—SOCI provides a class called Values specifically to facilitate this. The Values class acts as an intermediary between your custom aggregate class and the database. It provides get() and set() methods that allow you to define how your class maps to columns in the database. Listing Nine is a mapping of a Person struct to its database columns.

Listing Nine
#include "listing6.h"

#include <soci.h>
#include <boost/date_time/gregorian/gregorian.hpp>
using boost::gregorian::date;

struct Person
{
    int id;
    std::string name;
    date birthday;
};

namespace SOCI
{
template<> struct TypeConversion<Person>
{
    typedef Values base_type;
    static Person from(Values const &v)
    {
        Person p;
        p.id = v.get<int>("ID");
        p.name = v.get<std::string>("NAME");
        p.birthday = v.get<date>("BIRTHDAY");
        return p;
    }
    static Values to(Person &p)
    {
        Values v;
        v.set("ID", p.id);
        v.set("NAME", p.name);
        v.set("BIRTHDAY", p.birthday);
        return v;
    }
};
};

TypeConversion-based mappings to the Values class are simple to define, yet they provide a powerful and flexible means of abstraction. In fact, they provide a way to implement object-relational mapping, which is an area of much interest in the world of database programming using object-oriented languages (see Martin Fowler's Patterns of Enterprise Application Architecture; Addison-Wesley, 2002).

Listing Ten is a simple database access class that makes use of the TypeConversion<Person> specialization. The PersonDBStorage class provides methods GetPersonByName(), AddPerson(), and UpdatePerson(). As you can see, its implementation is simplified by the use of the TypeConversion-based object-relational mapping. If your class has more than a few data members, the simplicity gain from using such a mapping will be more pronounced.

Listing Ten
#include "listing6.h"
#include "listing9.h"

#include <soci.h>
#include <boost/date_time/gregorian/gregorian.hpp>

using namespace SOCI;
using boost::gregorian::date;

class PersonDBStorage
{
public:
    PersonDBStorage(SOCI::Session& sql) : mSql(sql) {}
    
    virtual Person getPersonByName(std::string& name)
    {
        Person p;
        mSql << "select * from Person where name = :NAME", use(name),
	        into(p);
	return p;
    }
	
    virtual void addPerson(Person& p)
    {
        mSql << "insert into Person values(:ID, :NAME, :BIRTHDAY)",
	        use(p);
    }

    virtual void updatePerson(Person& p)
    {
        mSql << "update Person set name = :NAME, " 
		"birthday = :BIRTHDAY where id = :ID", use(p);
    }
private:
    Session& mSql;
};

int main()
{
    try
    {
        Session sql("oracle", "service=gen1 user=scott"
                    " password=tiger");

        sql << "create table person(id number(5), name varchar2(20),"
               " birthday date)";

        PersonDBStorage storage(sql);

        Person p;
        p.id = 100;
        p.name = "Bjarne";
        p.birthday = date(2001, boost::gregorian::Jan, 1);
        storage.addPerson(p);

        Person p2 = storage.getPersonByName(p.name);
        assert(p2.birthday == p.birthday);
        std::cout << p2.name << "'s birthday is " << p2.birthday 
		  <<std::endl;

        sql << "drop table person";
    }
    catch(std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }
}

Conclusion

Supporting user customization via TypeConversion<T> is viable and potentially beneficial for any library that is driven by template specialization. The benefit is that it gives library users a succinct and noninvasive mechanism for making the library work transparently with their preferred user-defined types.

If you plan to implement TypeConversion support within your library, one technique to consider is to utilize a partial class template specialization for type TypeConversion<T>::base_type, which derives from the class template specialization for type T.

Acknowledgments

Thanks to Maciej Sobczak, founder of the SOCI project, for suggesting the use of the BaseValueHolder class in Listing Five.


Stephen is a Senior Software Engineer for Factor 5. He can be reached at www.featurecomplete.com.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.