❤️ SQLite ORM light header only library for modern C++
❤️ SQLite ORM light header only library for modern C++
| Branch | Travis | Appveyor |
|---|---|---|
master |
||
dev |
std::vector<char> or one can bind your custom type:memory: or empty filenamesqlite_orm library allows to create easy data model mappings to your database schema. It is built to manage (CRUD) objects with a primary key and without it. It also allows you to specify table names and column names explicitly no matter how your classes actually named. Take a look at example:
struct User{
int id;
std::string firstName;
std::string lastName;
int birthDate;
std::unique_ptr<std::string> imageUrl;
int typeId;
};
struct UserType {
int id;
std::string name;
};
So we have database with predefined schema like
CREATE TABLE users (id integer primary key autoincrement, first_name text not null, last_name text not null, birth_date integer not null, image_url text, type_id integer not null)
CREATE TABLE user_types (id integer primary key autoincrement, name text not null DEFAULT 'name_placeholder')
Now we tell sqlite_orm library about our schema and provide database filename. We create storage service object that has CRUD interface. Also we create every table and every column. All code is intuitive and minimalistic.
…Too easy isn't it? You do not have to specify mapped type explicitly - it is deduced from your member pointers you pass during making a column (for example: &User::id). To create a column you have to pass two arguments at least: its name in the table and your mapped class member pointer. You can also add extra arguments to tell your storage about column's constraints like primary_key, autoincrement, default_value, unique or generated_always_as (order isn't important; not_null/null are deduced from type automatically but can be added manually if you wish with null() and not_null()).
More details about making storage can be found in tutorial.
If your datamodel classes have private or protected members to map to sqlite then you can make a storage with setter and getter functions. More info in the example.
Let's create and insert new User into our database. First we need to create a User object with any id and call insert function. It will return id of just created user or throw exception if something goes wrong.
User user{-1, "Jonh", "Doe", 664416000, std::make_unique<std::string>("url_to_heaven"), 3 };
auto insertedId = storage.insert(user);
cout << "insertedId = " << insertedId << endl; // insertedId = 8
user.id = insertedId;
User secondUser{-1, "Alice", "Inwonder", 831168000, {} , 2};
insertedId = storage.insert(secondUser);
secondUser.id = insertedId;
Note: if we need to insert a new user with specified id call storage.replace(user); instead of insert.
Next let's get our user by id.
try{
auto user = storage.get<User>(insertedId);
cout << "user = " << user.firstName << " " << user.lastName << endl;
}catch(std::system_error e) {
cout << e.what() << endl;
}catch(...){
cout << "unknown exeption" << endl;
}Probably you may not like throwing exceptions. Me too. Exception std::system_error is thrown because return type in get function is not nullable. You can use alternative version get_pointer which returns std::unique_ptr and doesn't throw not_found_exception if nothing found - just returns nullptr.
if(auto user = storage.get_pointer<User>(insertedId)){
cout << "user = " << user->firstName << " " << user->lastName << endl;
}else{
cout << "no user with id " << insertedId << endl;
}std::unique_ptr is used as optional in sqlite_orm. Of course there is class optional in C++14 located at std::experimental::optional. But we don't want to use it until it is experimental.
We can also update our user. It updates row by id provided in user object and sets all other non primary_key fields to values stored in the passed user object. So you can just assign members to user object you want and call update
user.firstName = "Nicholas";
user.imageUrl = "https://cdn1.iconfinder.com/data/icons/man-icon-set/100/man_icon-21-512.png"
storage.update(user);Also there is a non-CRUD update version update_all:
storage.update_all(set(c(&User::lastName) = "Hardey",
c(&User::typeId) = 2),
where(c(&User::firstName) == "Tom"));And delete. To delete you have to pass id only, not whole object. Also we need to explicitly tell which class of object we want to delete. Function name is remove not delete cause delete is a reserved word in C++.
storage.remove<User>(insertedId)Also we can extract all objects into std::vector.
auto allUsers = storage.get_all<User>();
cout << "allUsers (" << allUsers.size() << "):" << endl;
for(auto &user : allUsers) {
cout << storage.dump(user) << endl; // dump returns std::string with json-like style object info. For example: { id : '1', first_name : 'Jonh', last_name : 'Doe', birth_date : '664416000', image_url : 'https://cdn1.iconfinder.com/data/icons/man-icon-set/100/man_icon-21-512.png', type_id : '3' }
}And one can specify return container type explicitly: let's get all users in std::list, not std::vector:
auto allUsersList = storage.get_all<User, std::list<User>>();Container must be STL compatible (must have push_back(T&&) function in this case).
get_all can be too heavy for memory so you can iterate row by row (i.e. object by object):
for(auto &user : storage.iterate<User>()) {
cout << storage.dump(user) << endl;
}iterate member function returns adapter object that has begin and end member functions returning iterators that fetch object on dereference operator call.
CRUD functions get, get_pointer, remove, update (not insert) work only if your type has a primary key column. If you try to get an object that is mapped to your storage but has no primary key column a std::system_error will be thrown cause sqlite_orm cannot detect an id. If you want to know how to perform a storage without primary key take a look at date_time.cpp example in examples folder.
Prepared statements are strongly typed.
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 8
auto selectStatement = storage.prepare(select(&Visit::doctor_id, where(length(&Visit::patient_name) > 8)));
cout << "selectStatement = " << selectStatement.sql() << endl; // prints "SELECT doctor_id FROM ..."
auto rows = storage.execute(selectStatement); // rows is std::vector<decltype(Visit::doctor_id)>
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 11
get<0>(selectStatement) = 11;
auto rows2 = storage.execute(selectStatement);get<N>(statement) function call allows you to access fields to bind them to your statement.
…You also can select objects with custom where conditions with =, !=, >, >=, <, <=, IN, BETWEEN and LIKE.
For example: let's select users with id lesser than 10:
// SELECT * FROM users WHERE id < 10
auto idLesserThan10 = storage.get_all<User>(where(c(&User::id) < 10));
cout << "idLesserThan10 count = " << idLesserThan10.size() << endl;
for(auto &user : idLesserThan10) {
cout << storage.dump(user) << endl;
}Or select all users who's first name is not equal "John":
// SELECT * FROM users WHERE first_name != 'John'
auto notJohn = storage.get_all<User>(where(c(&User::firstName) != "John"));
cout << "notJohn count = " << notJohn.size() << endl;
for(auto &user : notJohn) {
cout << storage.dump(user) << endl;
}By the way one can implement not equal in a different way using C++ negation operator:
auto notJohn2 = storage.get_all<User>(where(not (c(&User::firstName) == "John")));You can use ! and not in this case cause they are equal. Also you can chain several conditions with and and or operators. Let's try to get users with query with conditions like where id >= 5 and id <= 7 and not id = 6:
auto id5and7 = storage.get_all<User>(where(c(&User::id) <= 7 and c(&User::id) >= 5 and not (c(&User::id) == 6)));
cout << "id5and7 count = " << id5and7.size() << endl;
for(auto &user : id5and7) {
cout << storage.dump(user) << endl;
}Or let's just export two users with id 10 or id 16 (of course if these users exist):
auto id10or16 = storage.get_all<User>(where(c(&User::id) == 10 or c(&User::id) == 16));
cout << "id10or16 count = " << id10or16.size() << endl;
for(auto &user : id10or16) {
cout << storage.dump(user) << endl;
}In fact you can chain together any number of different conditions with any operator from and, or and not. All conditions are templated so there is no runtime overhead. And this makes sqlite_orm the most powerful sqlite C++ ORM library!
Moreover you can use parentheses to set the priority of query conditions:
…Also we can implement get by id with get_all and where like this:
// SELECT * FROM users WHERE ( 2 = id )
auto idEquals2 = storage.get_all<User>(where(2 == c(&User::id)));
cout << "idEquals2 count = " << idEquals2.size() << endl;
if(idEquals2.size()){
cout << storage.dump(idEquals2.front()) << endl;
}else{
cout << "user with id 2 doesn't exist" << endl;
}Lets try the IN operator:
// SELECT * FROM users WHERE id IN (2, 4, 6, 8, 10)
auto evenLesserTen10 = storage.get_all<User>(where(in(&User::id, {2, 4, 6, 8, 10})));
cout << "evenLesserTen10 count = " << evenLesserTen10.size() << endl;
for(auto &user : evenLesserTen10) {
cout << storage.dump(user) << endl;
}
// SELECT * FROM users WHERE last_name IN ("Doe", "White")
auto doesAndWhites = storage.get_all<User>(where(in(&User::lastName, {"Doe", "White"})));
cout << "doesAndWhites count = " << doesAndWhites.size() << endl;
for(auto &user : doesAndWhites) {
cout << storage.dump(user)No open issues yet, or sync has not completed.