Skip to content

Instantly share code, notes, and snippets.

@oliora
Last active March 3, 2016 23:50
Show Gist options
  • Save oliora/83d63c3d413b2972b0fc to your computer and use it in GitHub Desktop.
Save oliora/83d63c3d413b2972b0fc to your computer and use it in GitHub Desktop.
Concept of Simple ORM made with C++11
// Simple ORM = SORM
namespace sorm {
namespace details {
template<size_t N, class Statement, class P>
inline void bind_params(Statement& stmt, const P& p)
{
bind_param(stmt, N, p);
}
template<size_t N, class Statement, class P, class... Params>
inline void bind_params(Statement& stmt, const P& p, const Params&... params)
{
bind_param(stmt, N, p);
bind_params<N + 1>(stmt, params...);
}
template<size_t N, class ResultSet, class Field>
inline void load_fields(ResultSet& rs, Field& field)
{
load_field(field, N, rs);
}
template<size_t N, class ResultSet, class Field, class... Fields>
inline void load_fields(ResultSet& rs, Field& field, Fields&... fields)
{
load_field(field, N, rs);
load_fields<N + 1>(rs, fields...);
}
}
template<class ResultSet, class... Fields>
inline void load_fields(ResultSet& rs, Fields&... fields)
{
details::load_fields<1>(rs, fields...);
}
template<class Table, class Connection, class... Params>
inline Table load_table(Connection& con, const std::string& tag, const std::string& sql, const Params&... params)
{
auto stmt = con.createStatement(tag, sql);
details::bind_params<1>(stmt, params...);
auto result_set = stmt_.execute()
Table table;
while (result_set.next())
{
typename Table::mapped_type row;
load(row, rs);
table.emplace(get_primary_key(row), std::move(row));
}
return table;
}
template<class Row>
using basic_table = std::map<typename std::remove_reference<decltype(get_primary_key(std::declval<Row>()))>::type, Row>;
} // namespace sorm
////////////////////////////////////////////
// Usage
struct Message {
int messageid;
int userid;
std::string title;
};
template<class ResultSet>
inline void load(Message& msg, ResultSet& rs)
{
sorm::load_fields(rs, msg.messageid, msg.userid, msg.title);
}
inline const std::string& get_primary_key(const Message& msg) { return msg.messageid; }
using Messages = sorm::basic_table<Message>;
template<class Connection>
inline Messages load_messages_by_id(Connection& con, int userid)
{
return sorm::load_table<Messages>(con, __FUNCTION__, "select messageid, userid, title from messages where userid = :userid", userid);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment