db_mongoc.h
浏览该文件的文档.
1/*!
2 * \file db_mongoc.h
3 * \brief Simple wrappers of the API of MongoDB C driver `mongo-c-driver`,
4 * see <a href="http://mongoc.org/">MongoDB C Driver</a> for more information.
5 *
6 * \remarks
7 * - 1. 2017-12-02 - lj - Add unittest based on gtest/gmock.
8 * - 2. 2018-05-02 - lj - Make part of CCGL.
9 * - 3. 2019-08-16 - lj - Simplify brief desc. and move detail desc. to implementation.
10 *
11 * \note No exceptions will be thrown.
12 * \author Liangjun Zhu, zlj(at)lreis.ac.cn
13 * \version 1.2
14 */
15#ifndef CCGL_DB_MONGOC_H
16#define CCGL_DB_MONGOC_H
17#ifdef USE_MONGODB
18
19#include <vector>
20#include <map>
21#include <iostream>
22
23#include <mongoc.h>
24
25#include "basic.h"
26
27using std::string;
28using std::vector;
29using std::map;
30using std::cout;
31using std::endl;
32
33namespace ccgl {
34/*!
35 * \namespace ccgl::db_mongoc
36 * \brief Simple wrappers of the API of MongoDB C driver `mongo-c-driver`,
37 * see <a href="http://mongoc.org/">MongoDB C Driver</a> for more information.
38 */
39namespace db_mongoc {
40class MongoGridFs;
41
42/*!
43 * \class MongoClient
44 * \brief A simple wrapper of the class of MongoDB Client `mongoc_client_t`.
45 */
47public:
48 /*! Constructor using IP address and port number */
49 MongoClient(const char* host, vuint16_t port);
50
51 /*! Constructor using mongoc_client_t* */
52 MongoClient(mongoc_client_t* conn);
53
54 /*! Initialization of MongoClient with the validation check of database */
55 static MongoClient* Init(const char* host, vuint16_t port);
56
57 /*! Destructor */
59
60 /*! Destroy explicitly */
61 void Destroy();
62
63 /*! Get `mongoc_client_t` instance */
64 mongoc_client_t* GetConn() { return conn_; }
65
66 /*! Get existing or newly created `mongoc_database_t` instance */
67 mongoc_database_t* GetDatabase(string const& dbname);
68
69 /*! Get `mongoc_collection_t` instance */
70 mongoc_collection_t* GetCollection(string const& dbname, string const& collectionname);
71
72 /*! Get `mongoc_gridfs_t` instance */
73 mongoc_gridfs_t* GetGridFs(string const& dbname, string const& gfsname);
74
75 /*! Get MongoGridFs instance */
76 MongoGridFs* GridFs(string const& dbname, string const& gfsname);
77
78 /*! Get existing database names */
79 void GetDatabaseNames(vector<string>& dbnames);
80
81 /*! Get collection names in MongoDB database */
82 void GetCollectionNames(string const& dbname, vector<string>& collnames);
83
84 /*! Get GridFs file names in MongoDB database */
85 void GetGridFsFileNames(string const& dbname, string const& gfsname, vector<string>& gfs_exists);
86
87private:
88 const char* host_; ///< Host IP address of MongoDB
89 vuint16_t port_; ///< Port number
90 mongoc_client_t* conn_; ///< Instance of `mongoc_client_t`
91};
92
93/*!
94 * \class MongoDatabase
95 * \brief A simple wrapper of the class of MongoDB database `mongoc_database_t`.
96 */
98public:
99 /*! Constructor by a `mongoc_database_t` pointer */
100 explicit MongoDatabase(mongoc_database_t* db);
101
102 /*! Constructor by mongodb client (`mongoc_client_t` pointer) and database name */
103 MongoDatabase(mongoc_client_t* conn, string& dbname);
104
105 /*! Destructor */
107
108 /*! Get collection names in current database */
109 void GetCollectionNames(vector<string>& collnames);
110
111private:
112 mongoc_database_t* db_; ///< Instance of `mongoc_database_t`
113 string dbname_; ///< Database name
114};
115
116/*!
117* \class MongoCollection
118* \brief A simple wrapper of the class of MongoDB Collection `mongoc_collection_t`.
119*/
121public:
122 /*! Constructor by a `mongoc_collection_t` pointer */
123 explicit MongoCollection(mongoc_collection_t* coll);
124
125 /*! Destructor */
127
128 /*! Execute query */
129 mongoc_cursor_t* ExecuteQuery(const bson_t* b, const bson_t* opts = nullptr);
130
131 /*! Query the records number */
133private:
134 mongoc_collection_t* collection_; ///< Instance of `mongoc_collection_t`
135};
136
137/*!
138 * \class MongoGridFs
139 * \brief A simple wrapper of the class of MongoDB database `mongoc_gridfs_t`.
140 */
142public:
143 /*! Constructor by a `mongoc_gridfs_t` pointer or NULL */
144 explicit MongoGridFs(mongoc_gridfs_t* gfs = NULL);
145
146 /*! Destructor */
148
149 /*! Get the current instance of `mongoc_gridfs_t` */
150 mongoc_gridfs_t* GetGridFs() { return gfs_; }
151
152 /*! Get GridFS file by name */
153 mongoc_gridfs_file_t* GetFile(string const& gfilename, mongoc_gridfs_t* gfs = NULL,
154 const STRING_MAP& opts = STRING_MAP());
155
156 /*! Remove GridFS all matching files and their data chunks. */
157 bool RemoveFile(string const& gfilename, mongoc_gridfs_t* gfs = NULL,
158 STRING_MAP opts = STRING_MAP());
159
160 /*! Get GridFS file names */
161 void GetFileNames(vector<string>& files_existed, mongoc_gridfs_t* gfs = NULL,
162 STRING_MAP opts = STRING_MAP());
163
164 /*! Get metadata of a given GridFS file name, remember to destory bson_t after use */
165 bson_t* GetFileMetadata(string const& gfilename, mongoc_gridfs_t* gfs = NULL,
166 STRING_MAP opts = STRING_MAP());
167
168 /*! Get stream data of a given GridFS file name */
169 bool GetStreamData(string const& gfilename, char*& databuf, vint& datalength,
170 mongoc_gridfs_t* gfs = NULL,
171 const STRING_MAP* opts = nullptr);
172
173 /*! Write stream data to a GridFS file */
174 bool WriteStreamData(const string& gfilename, char*& buf, vint length,
175 const bson_t* p, mongoc_gridfs_t* gfs = NULL);
176
177private:
178 mongoc_gridfs_t* gfs_; ///< Instance of `mongoc_gridfs_t`
179};
180
181/*! Append options to `bson_t` */
182void AppendStringOptionsToBson(bson_t* bson_opts, const STRING_MAP& opts,
183 const string& prefix = string());
184
185/*!
186 * \brief Get numeric value from the iterator (`bson_iter_t`) of `bson_t`according to a given key
187 * \param[in] iter Iterator of an instance of `bson_t`
188 * \param[in,out] numericvalue The extracted value which can be `int`, `float`, or `double`
189 * \return true if succeed, otherwise false.
190 */
191template <typename T>
192bool GetNumericFromBsonIterator(bson_iter_t* iter, T& numericvalue) {
193 const bson_value_t* vv = bson_iter_value(iter);
194 if (vv->value_type == BSON_TYPE_INT32) {
195 numericvalue = static_cast<T>(vv->value.v_int32);
196 } else if (vv->value_type == BSON_TYPE_INT64) {
197 numericvalue = static_cast<T>(vv->value.v_int64);
198 } else if (vv->value_type == BSON_TYPE_DOUBLE) {
199 numericvalue = static_cast<T>(vv->value.v_double);
200 } else if (vv->value_type == BSON_TYPE_UTF8) {
201 string tmp = vv->value.v_utf8.str;
202 if (tmp.find_first_of("0123456789") == string::npos) {
203 cout << "bson iterator isn't or not contains a numeric value." << endl;
204 return false;
205 }
206 char* end = nullptr;
207 numericvalue = static_cast<T>(strtod(tmp.c_str(), &end));
208 } else {
209 cout << "bson iterator isn't or not contains a numeric value." << endl;
210 return false;
211 }
212 return true;
213}
214
215/*!
216parse the following nested vector from bson_t:
217[1, 2, 3]
218 */
219template<typename T>
220void GetVectorFromBsonIter(bson_iter_t* iter, vector<T>& out){
221 const bson_value_t* vv = bson_iter_value(iter);
222 T value;
223 if (vv->value_type == BSON_TYPE_ARRAY) {
224 bson_iter_t sub_iter;
225 bson_iter_recurse(iter, &sub_iter);
226 while (bson_iter_next(&sub_iter)) {
227 const bson_value_t* sub_vv = bson_iter_value(&sub_iter);
228 if (sub_vv->value_type == BSON_TYPE_INT32) {
229 out.emplace_back(CVT_INT(sub_vv->value.v_int32));
230 } else if (sub_vv->value_type == BSON_TYPE_INT64) {
231 out.emplace_back(CVT_INT(sub_vv->value.v_int64));
232 } else if (sub_vv->value_type == BSON_TYPE_DOUBLE) {
233 out.emplace_back(sub_vv->value.v_double);
234 } else {
235 StatusMessage("Failed in get vector value in the inner loop of GetVectorFromBsonIter.");
236 }
237 }
238 }
239 else if (GetNumericFromBsonIterator(iter, value)){
240 out.emplace_back(value);
241 }
242 else {
243 StatusMessage("Failed in get vector value in the outer loop of GetVectorFromBsonIter.");
244 }
245}
246
247/*!
248parse the following nested vector from bson_t:
249[
250 [1, 2, 3],
251 [4, 5, 6],
252 [7, 8, 9]
253]
254 */
255template<typename T>
256void GetVectorVectorFromBsonIter(bson_iter_t* iter, vector<vector<T>>& out){
257 const bson_value_t* vv = bson_iter_value(iter);
258 T value;
259 if (vv->value_type == BSON_TYPE_ARRAY) {
260 bson_iter_t sub_iter;
261 bson_iter_recurse(iter, &sub_iter);
262 while (bson_iter_next(&sub_iter)) {
263 vector<T> tmp;
264 GetVectorFromBsonIter(&sub_iter, tmp);
265 out.emplace_back(tmp);
266 }
267 }
268 else if (GetNumericFromBsonIterator(iter, value)) {
269 vector<T> tmp;
270 tmp.emplace_back(value);
271 out.emplace_back(tmp);
272 }
273 else {
274 StatusMessage("Failed in get vector value.");
275 }
276}
277
278/*!
279 * \brief Get numeric value from `bson_t` according to a given key
280 * \param[in] bmeta Instance of `bson_t`
281 * \param[in] key
282 * \param[in,out] numericvalue The extracted value which can be `int`, `float`, or `double`
283 * \return true if succeed, otherwise false.
284 * \sa GetNumericFromBsonIterator()
285 */
286template <typename T>
287bool GetNumericFromBson(bson_t* bmeta, const char* key, T& numericvalue) {
288 bson_iter_t iter;
289 if (bson_iter_init(&iter, bmeta) && bson_iter_find(&iter, key)) {
290 return GetNumericFromBsonIterator(&iter, numericvalue);
291 }
292 StatusMessage(("WARNING: GetNumericFromBson, Failed in get value of: " + string(key) + "\n").c_str());
293 return false;
294}
295
296/*!
297 * \brief Get String from the iterator (`bson_iter_t`) of `bson_t`
298 * \param[in] iter Iterator of an instance of `bson_t`
299 * \return String of value if succeed, otherwise empty string ("").
300 */
301string GetStringFromBsonIterator(bson_iter_t* iter);
302
303/*!
304 * \brief Get String from `bson_t`
305 * \param[in] bmeta Instance of `bson_t`
306 * \param[in] key
307 * \return String of value if succeed, otherwise empty string ("").
308 * \sa GetStringFromBsonIterator()
309 */
310string GetStringFromBson(bson_t* bmeta, const char* key);
311
312/*!
313 * \brief Get Bool from the iterator (`bson_iter_t`) of `bson_t`
314 * \param[in] iter Iterator of an instance of `bson_t`
315 * \return true if succeed, otherwise false.
316 */
317bool GetBoolFromBsonIterator(bson_iter_t* iter);
318
319/*!
320 * \brief Get String from `bson_t`
321 * \param[in] bmeta Instance of `bson_t`
322 * \param[in] key
323 * \return true if succeeded, otherwise false.
324 * \sa GetBoolFromBsonIterator()
325 */
326bool GetBoolFromBson(bson_t* bmeta, const char* key);
327
328/*!
329 * \brief Get Datetime from the iterator (`bson_iter_t`) of `bson_t`
330 * \param[in] iter Iterator of an instance of `bson_t`
331 * \return float value (`time_t`) if succeed, otherwise -1.
332 */
333time_t GetDatetimeFromBsonIterator(bson_iter_t* iter);
334
335/*!
336 * \brief Get Datetime from `bson_t`
337 * \param[in] bmeta Instance of `bson_t`
338 * \param[in] key
339 * \return float value (`time_t`) if succeed, otherwise -1.
340 * \sa GetDatetimeFromBsonIterator()
341 */
342time_t GetDatetimeFromBson(bson_t* bmeta, const char* key);
343} /* namespace: db_mongoc */
344} /* namespace: ccgl */
345
346#endif /* USE_MONGODB */
347#endif /* CCGL_DB_MONGOC_H */
Basic definitions.
#define CVT_INT(param)
A reference to the postfix of executable file for RELWITHDEBINFO mode
Definition: basic.h:325
Base class for classes that cannot be copied.
Definition: basic.h:385
A simple wrapper of the class of MongoDB Client mongoc_client_t.
Definition: db_mongoc.h:46
MongoClient(mongoc_client_t *conn)
Constructor using mongoc_client_t*
void GetDatabaseNames(vector< string > &dbnames)
Get existing database names
mongoc_database_t * GetDatabase(string const &dbname)
Get existing or newly created mongoc_database_t instance
mongoc_collection_t * GetCollection(string const &dbname, string const &collectionname)
Get mongoc_collection_t instance
mongoc_client_t * GetConn()
Get mongoc_client_t instance
Definition: db_mongoc.h:64
MongoClient(const char *host, vuint16_t port)
Constructor using IP address and port number
void Destroy()
Destroy explicitly
mongoc_gridfs_t * GetGridFs(string const &dbname, string const &gfsname)
Get mongoc_gridfs_t instance
static MongoClient * Init(const char *host, vuint16_t port)
Initialization of MongoClient with the validation check of database
void GetGridFsFileNames(string const &dbname, string const &gfsname, vector< string > &gfs_exists)
Get GridFs file names in MongoDB database
MongoGridFs * GridFs(string const &dbname, string const &gfsname)
Get MongoGridFs instance
void GetCollectionNames(string const &dbname, vector< string > &collnames)
Get collection names in MongoDB database
A simple wrapper of the class of MongoDB Collection mongoc_collection_t.
Definition: db_mongoc.h:120
mongoc_cursor_t * ExecuteQuery(const bson_t *b, const bson_t *opts=nullptr)
Execute query
MongoCollection(mongoc_collection_t *coll)
Constructor by a mongoc_collection_t pointer
vint QueryRecordsCount()
Query the records number
A simple wrapper of the class of MongoDB database mongoc_database_t.
Definition: db_mongoc.h:97
MongoDatabase(mongoc_database_t *db)
Constructor by a mongoc_database_t pointer
void GetCollectionNames(vector< string > &collnames)
Get collection names in current database
MongoDatabase(mongoc_client_t *conn, string &dbname)
Constructor by mongodb client (mongoc_client_t pointer) and database name
A simple wrapper of the class of MongoDB database mongoc_gridfs_t.
Definition: db_mongoc.h:141
bool RemoveFile(string const &gfilename, mongoc_gridfs_t *gfs=NULL, STRING_MAP opts=STRING_MAP())
Remove GridFS all matching files and their data chunks.
mongoc_gridfs_file_t * GetFile(string const &gfilename, mongoc_gridfs_t *gfs=NULL, const STRING_MAP &opts=STRING_MAP())
Get GridFS file by name
MongoGridFs(mongoc_gridfs_t *gfs=NULL)
Constructor by a mongoc_gridfs_t pointer or NULL
bool GetStreamData(string const &gfilename, char *&databuf, vint &datalength, mongoc_gridfs_t *gfs=NULL, const STRING_MAP *opts=nullptr)
Get stream data of a given GridFS file name
bool WriteStreamData(const string &gfilename, char *&buf, vint length, const bson_t *p, mongoc_gridfs_t *gfs=NULL)
Write stream data to a GridFS file
bson_t * GetFileMetadata(string const &gfilename, mongoc_gridfs_t *gfs=NULL, STRING_MAP opts=STRING_MAP())
Get metadata of a given GridFS file name, remember to destory bson_t after use
void GetFileNames(vector< string > &files_existed, mongoc_gridfs_t *gfs=NULL, STRING_MAP opts=STRING_MAP())
Get GridFS file names
mongoc_gridfs_t * GetGridFs()
Get the current instance of mongoc_gridfs_t
Definition: db_mongoc.h:150
void GetVectorVectorFromBsonIter(bson_iter_t *iter, vector< vector< T > > &out)
parse the following nested vector from bson_t: [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
Definition: db_mongoc.h:256
bool GetNumericFromBson(bson_t *bmeta, const char *key, T &numericvalue)
Get numeric value from bson_t according to a given key
Definition: db_mongoc.h:287
void AppendStringOptionsToBson(bson_t *bson_opts, const STRING_MAP &opts, const string &prefix=string())
Append options to bson_t
string GetStringFromBsonIterator(bson_iter_t *iter)
Get String from the iterator (bson_iter_t) of bson_t
bool GetBoolFromBsonIterator(bson_iter_t *iter)
Get Bool from the iterator (bson_iter_t) of bson_t
time_t GetDatetimeFromBsonIterator(bson_iter_t *iter)
Get Datetime from the iterator (bson_iter_t) of bson_t
string GetStringFromBson(bson_t *bmeta, const char *key)
Get String from bson_t
bool GetNumericFromBsonIterator(bson_iter_t *iter, T &numericvalue)
Get numeric value from the iterator (bson_iter_t) of bson_taccording to a given key
Definition: db_mongoc.h:192
time_t GetDatetimeFromBson(bson_t *bmeta, const char *key)
Get Datetime from bson_t
bool GetBoolFromBson(bson_t *bmeta, const char *key)
Get String from bson_t
void GetVectorFromBsonIter(bson_iter_t *iter, vector< T > &out)
parse the following nested vector from bson_t: [1, 2, 3]
Definition: db_mongoc.h:220
Common Cross-platform Geographic Library (CCGL)
std::map< string, string > STRING_MAP
Map of string key and string value
Definition: basic.h:349
void StatusMessage(const char *msg)
Print status messages for Debug