knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
BulkOperation.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/BulkOperation.h"
7 #include "knowrob/storage/mongo/MongoException.h"
8 
9 using namespace knowrob::mongo;
10 
11 BulkOperation::BulkOperation(mongoc_bulk_operation_t *handle)
12  : handle_(handle) {
13 }
14 
16  if (handle_) {
17  mongoc_bulk_operation_destroy(handle_);
18  handle_ = nullptr;
19  }
20 }
21 
23  if (!handle_) {
24  bson_error_t err;
25  bson_set_error(&err,
26  MONGOC_ERROR_COMMAND,
27  MONGOC_ERROR_COMMAND_INVALID_ARG,
28  "bulk operation can only be executed once");
29  throw MongoException("bulk_operation", err);
30  }
31 }
32 
33 void BulkOperation::pushInsert(const bson_t *document) {
35 
36  bson_error_t err;
37  if (!mongoc_bulk_operation_insert_with_opts(
38  handle_,
39  document,
40  nullptr,
41  &err)) {
42  throw MongoException("bulk_operation", err);
43  }
44  empty_ = false;
45 }
46 
47 void BulkOperation::pushRemoveOne(const bson_t *document) {
49 
50  bson_error_t err;
51  if (!mongoc_bulk_operation_remove_one_with_opts(
52  handle_,
53  document,
54  nullptr,
55  &err)) {
56  throw MongoException("bulk_operation", err);
57  }
58  empty_ = false;
59 }
60 
61 void BulkOperation::pushRemoveAll(const bson_t *document) {
63 
64  bson_error_t err;
65  if (!mongoc_bulk_operation_remove_many_with_opts(
66  handle_,
67  document,
68  nullptr,
69  &err)) {
70  throw MongoException("bulk_operation", err);
71  }
72  empty_ = false;
73 }
74 
75 void BulkOperation::pushUpdate(bson_t *query, bson_t *update) {
77 
78  bson_error_t err;
79  if (!mongoc_bulk_operation_update_many_with_opts(
80  handle_,
81  query,
82  update,
83  nullptr,
84  &err)) {
85  throw MongoException("bulk_operation", err);
86  }
87  empty_ = false;
88 }
89 
90 
93 
94  bson_error_t bulk_err;
95  bson_t bulk_reply;
96  // perform the bulk write
97  bool success = mongoc_bulk_operation_execute(handle_, &bulk_reply, &bulk_err);
98  // cleanup
99  bson_destroy(&bulk_reply);
100  mongoc_bulk_operation_destroy(handle_);
101  handle_ = nullptr;
102  // throw exception on error
103  if (!success) {
104  throw MongoException("bulk_operation", bulk_err);
105  }
106 }
void pushRemoveOne(const bson_t *document)
void pushInsert(const bson_t *document)
mongoc_bulk_operation_t * handle_
Definition: BulkOperation.h:67
void pushUpdate(bson_t *query, bson_t *update)
BulkOperation(mongoc_bulk_operation_t *handle)
void pushRemoveAll(const bson_t *document)