Loading database with data inside
JakeAbo opened this issue · 1 comments
JakeAbo commented
Hey,
It would be very nice if there will be functionality to read database with data inside it(with records in tables).
Instead of creating database every single program.
Thanks a lot,
jack
d-led commented
it's already possible. Check this out:
#include "hiberlite.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
struct Counter {
friend class hiberlite::access;
template<class Archive>
void hibernate(Archive & ar)
{
ar & HIBERLITE_NVP(count);
}
int count = 0;
};
HIBERLITE_EXPORT_CLASS(Counter)
void example() {
hiberlite::Database db("sample.db");
db.registerBeanClass<Counter>();
try {
db.createModel();
}
catch (std::exception& e) {
std::cout << "didn't create the tables: " << e.what()<< ::endl;
}
// create item if missing
std::vector< hiberlite::bean_ptr<Counter> > v = db.getAllBeans<Counter>();
if (v.size() == 0) {
auto p = db.copyBean(Counter{ 0 });
}
v = db.getAllBeans<Counter>();
auto p = *v.begin();
p->count = p->count + 1;
std::cout << "counter now at: " << p->count << std::endl;
}
int main()
{
try {
example();
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
↓
first run:
counter now at: 1
second run:
didn't create the tables: table Counter already exists
counter now at: 2