Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ SOCI query into vector of custom Object

Tags:

c++

soci

Currently I'm writing a C++ application where I have to connect to a SQLite database. I search for a library and found SOCI and I have to say: I love it. The stream syntax and the mapping is so awesome. But I have one problem with it:

I have an Event class and I've written the parser functions for it:

template<> struct type_conversion<Event>
{
    typedef values base_type;

    static void from_base(const values& v, indicator /* ind */, Event& event)
    {
        event.m_id = v.get<std::string>("id");
        event.m_title = v.get<std::string>("Title");
        event.m_description = v.get<std::string>("Description");
        event.m_date = v.get<std::tm>("Date");
    }

    static void to_base(const Event& event, values& v, indicator& ind)
    {
        v.set("id", event.m_id);
        v.set("Title", event.m_title);
        v.set("Description", event.m_description);
        v.set("Date", event.m_date);

        ind = i_ok;
    }
};

This works great for queries like this:

sql << "SELECT * FROM Event WHERE id=5", into(event); 

I would like to select a bulk of Events into a std::vector<Event*> but if I try this with:

std::vector<Event*> events;
sql << "SELECT * FROM Event", into(events)

But with this I get following compiler error:

No known convertation from
soci::details::conversion_into_type<std::vector<Event>> into
soci::details::into_type_base

Isn't that possible with SOCI or am I missing something? I also found OTL as library. Is that maybe a good alternative? As I said I like the SOCI way. Is something like this also possible with OTL?

like image 737
Cilenco Avatar asked Feb 15 '17 22:02

Cilenco


1 Answers

SOCI does not support combination of ORM with bulk operations. See the mailing list thread: ORM with std::vector not supported?.

Instead, you can use rowset and iterator-based access:

rowset<Event> rs = (sql.prepare << "SELECT * FROM Event");
for (auto it = rs.cbegin(); it != rs.cend(); ++it)
{
   // access event
}

AFAIR, it still should be supported.

like image 58
mloskot Avatar answered Oct 21 '22 19:10

mloskot