-
-
Notifications
You must be signed in to change notification settings - Fork 321
storage_t::get_no_throw
template<class O, class I>
std::shared_ptr<O> get_no_throw(I id);
Select * by id routine. This is a basic function for CRUD get by id just like normal get but this function doesn't throw an exception if row not found but returns nullable type (std::shared_ptr
now but once C++17 becomes stable it's gonna be changed to std::optional
) which equals nullptr
if nothing found and equals value if something is found. It can throw std::runtime_error
if something is wrong just like any other sqlite_orm
function anyway.
class O is a mapped type you expect to return. Must be specified explicitly.
class I primary key class. Sqlite expects int as id but you can use string if you like.
(1) id
id of object you expect to return. Note that column may have any name (not "id") but it must have PRIMARY KEY
option in the storage and in the db. It is enough to specify primary_key in make_column and call sync_schema to meet this conditions.
std::shared_ptr
with value with specified id or nullptr
if nothing found.
struct Tweet {
int id;
std::string text;
std::string date;
};
using namespace sqlite_orm;
auto storage = make_storage("tweets.sqlite",
make_table("tweets",
make_column("id",
&Tweet::id,
primary_key()),
make_column("text",
&Tweet::text),
make_column("date",
&Tweet::date)));
storage.sync_schema();
// remove all old tweet if they do exist
storage.remove_all<Tweet>();
auto insertedId = storage.insert(Tweet{
-1,
"I use sqlite_orm!",
storage.current_timestamp(),
});
// now we have only one tweet in 'tweets' table with id = insertedId
auto justInsertedTweet = storage.get_no_throw<Tweet>(insertedId);
cout << "tweet with id " << insertedId << (bool(justInsertedTweet) ? " exists" : " doesn't exist") << endl;
if(justInsertedTweet){
cout << storage.dump(*justInsertedTweet) << endl;
}
auto notExistingId = insertedId + 1;
auto notExistingTweet = storage.get_no_throw<Tweet>(notExistingId);
cout << "tweet with id " << notExistingId << (bool(notExistingTweet) ? " exists" : " doesn't exist") << endl;
if(notExistingTweet){
cout << storage.dump(*notExistingTweet) << endl;
}