knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
MongoInterface.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 <mongoc.h>
7 #include <sstream>
8 
9 #include "knowrob/storage/mongo/MongoInterface.h"
10 
11 using namespace knowrob::mongo;
12 
13 MongoInterface::MongoInterface() {
14  mongoc_init();
15 }
16 
17 MongoInterface::~MongoInterface() = default;
18 
20  static MongoInterface singleton;
21  return singleton;
22 }
23 
24 std::shared_ptr<Connection> MongoInterface::getOrCreateConnection(const char *uri_string_c) {
25  std::string uri_string(uri_string_c);
26  auto it = connections_.find(uri_string);
27  if (it == connections_.end()) {
28  // create a new connection
29  auto newConnection = std::make_shared<Connection>(uri_string);
30  connections_[uri_string] = newConnection;
31  return newConnection;
32  } else {
33  return it->second;
34  }
35 }
36 
37 std::shared_ptr<Database> MongoInterface::connect(const PlTerm &dbTerm) {
38  auto dbConnection = getOrCreateConnection((char *) dbTerm[1]);
39  return std::make_shared<Database>(dbConnection->pool_, (char *) dbTerm[2]);
40 }
41 
42 std::shared_ptr<Collection> MongoInterface::connect(const PlTerm &dbTerm, const char *collectionName) {
43  return connect((char *) dbTerm[1], (char *) dbTerm[2], collectionName);
44 }
45 
46 std::shared_ptr<Collection>
47 MongoInterface::connect(const char *db_uri, const char *db_name, const char *collectionName) {
48  auto dbConnection = getOrCreateConnection(db_uri);
49  return std::make_shared<Collection>(dbConnection, db_name, collectionName);
50 }
51 
52 
53 std::shared_ptr<Cursor> MongoInterface::cursor_create(const PlTerm &db_term, const char *coll_name) {
54  auto coll = connect(db_term, coll_name);
55  auto c = std::make_shared<Cursor>(coll);
56  std::lock_guard<std::mutex> scoped_lock(mongo_mutex_);
57  cursors_[c->id()] = c;
58  return c;
59 }
60 
61 void MongoInterface::cursor_destroy(const char *curser_id) {
62  std::lock_guard<std::mutex> scoped_lock(mongo_mutex_);
63  cursors_.erase(curser_id);
64 }
65 
66 std::shared_ptr<Cursor> MongoInterface::cursor(const char *curser_id) {
67  std::lock_guard<std::mutex> scoped_lock(mongo_mutex_);
68  return cursors_[std::string(curser_id)];
69 }
70 
std::shared_ptr< Database > connect(const PlTerm &dbTerm)
std::shared_ptr< Cursor > cursor_create(const PlTerm &db_term, const char *coll_name)
std::shared_ptr< Cursor > cursor(const char *curser_id)
static MongoInterface & get()
void cursor_destroy(const char *curser_id)
TermRule & string()
Definition: terms.cpp:63