Skip to content

storage_t::get

Yevgeniy Zakharov edited this page Mar 30, 2017 · 6 revisions
template<class O, class I>
O get(I id);

Select * by id routine. This is a basic function for CRUD get by id.

Throws

sqlite_orm::not_found_exeption if object not found with given id.

std::runtime_error in case of db error

Parameters

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.

Return value

Value with specified id.

Example

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 love sqlite_orm!",
    storage.current_timestamp(),
});

try {
    auto justInsertedTweet = storage.get<Tweet>(insertedId);
    cout << storage.dump(justInsertedTweet) << endl;
    
    auto notExistingTweet = storage.get<Tweet>(insertedId + 1);
    cout << "This line will never be printed out" << endl;
    assert(0);
}catch(sqlite_orm::not_found_exception e) {
    cout << e.what() << endl;
}

Clone this wiki locally