knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
Database.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of KnowRob, please consult
3  * https://github.com/knowrob/knowrob for license details.
4  */
5 
6 #include <knowrob/storage/mongo/Database.h>
7 #include <knowrob/storage/mongo/MongoException.h>
8 
9 using namespace knowrob::mongo;
10 
11 Database::Database(mongoc_client_pool_t *pool, std::string_view db_name)
12  : pool_(pool) {
13  client_ = mongoc_client_pool_pop(pool_);
14  db_ = mongoc_client_get_database(client_, db_name.data());
15 }
16 
18  mongoc_database_destroy(db_);
19  mongoc_client_pool_push(pool_, client_);
20 }
21 
22 bool Database::create_index(const char *coll_name, const std::vector<IndexKey> &indexes) {
23  bson_t reply;
24  bson_error_t err;
25  bson_t keys;
26  //
27  bson_init(&keys);
28  for (auto &is : indexes) {
29  BSON_APPEND_INT32(&keys, is.value.c_str(), (int)is.type);
30  }
31  char *index_name = mongoc_collection_keys_to_index_string(&keys);
32  //
33  bson_t *cmd = BCON_NEW ("createIndexes", BCON_UTF8(coll_name),
34  "indexes", "[", "{",
35  "key", BCON_DOCUMENT(&keys),
36  "name", BCON_UTF8(index_name),
37  "}", "]"
38  );
39  bool success = mongoc_database_write_command_with_opts(
40  db_, cmd, nullptr /* opts */, &reply, &err);
41  bson_free(index_name);
42  bson_destroy(&reply);
43  bson_destroy(cmd);
44  if (!success) {
45  throw MongoException("create_index_failed", err);
46  }
47  return success;
48 }
Database(mongoc_client_pool_t *pool, std::string_view db_name)
Definition: Database.cpp:11
bool create_index(const char *coll_name, const std::vector< IndexKey > &indexes)
Definition: Database.cpp:22