-
Notifications
You must be signed in to change notification settings - Fork 14
/
BSON.cpp
109 lines (102 loc) · 3.23 KB
/
BSON.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <QDebug>
#include "BSON.h"
#include "QMongoDriver.h"
QVariantMap fromBson(mongo::BSONObj bson) {
QVariantMap obj;
for(mongo::BSONObjIterator i(bson); i.more();) {
mongo::BSONElement e = i.next();
QString name = QString::fromStdString(e.fieldName());
switch(e.type()) {
case mongo::EOO:
return obj;
case mongo::NumberDouble:
obj[name] = e.numberDouble();
break;
case mongo::String:
obj[name] = QString::fromStdString(e.str());
break;
case mongo::Object:
obj[name] = fromBson(e.embeddedObject());
break;
case mongo::Date:
obj[name] = QDateTime::fromTime_t(e.date());
break;
case mongo::Undefined:
obj[name] = QVariant();
break;
case mongo::jstOID:
obj[name] = QString::fromStdString(e.__oid().str());
break;
case mongo::jstNULL:
obj[name] = QVariant();
break;
case mongo::Bool:
obj[name] = e.boolean();
break;
case mongo::CodeWScope:
obj[name] = "MongoCode["+QString::fromStdString(e.codeWScopeCode())+"]";
break;
case mongo::NumberInt:
obj[name] = e.numberInt();
break;
default:
qCritical() << "fromBson() type" << e.type() << "unknown!";
Q_ASSERT(false);
}
}
return obj;
}
mongo::BSONObj toBson(QVariantMap obj) {
mongo::BSONObjBuilder b;
QVariantMap::iterator it = obj.begin();
while(it != obj.end()) {
QByteArray byteName = it.key().toStdString().c_str();
const char* name = byteName.constData();
QVariant v = it.value();
int type = v.type();
// qDebug() << "toBson converting type" << v.typeName();
if (v.canConvert<QObject*>()) {
QMongoType* mongo = qobject_cast<QMongoType*>( v.value<QObject*>() );
Q_ASSERT(mongo->o.nFields() == 1);
b.appendAs(mongo->o.firstElement(), name);
++it;
continue;
}
bool ok = true;
switch(type) {
case QVariant::Int:
b.append(name, v.toInt(&ok));
break;
case QVariant::String:
b.append(name, v.toString().toStdString());
break;
case QVariant::LongLong:
b.append(name, v.toLongLong(&ok));
break;
case QVariant::UInt:
b.append(name, v.toUInt(&ok));
break;
case QVariant::Map:
b.append(name, toBson(v.toMap()));
break;
case QVariant::Double:
b.append(name, v.toDouble(&ok));
break;
case QVariant::Bool:
b.appendBool(name, v.toBool());
break;
case QVariant::Time:
b.appendTimeT(name, v.toDateTime().toTime_t());
break;
case QVariant::Invalid:
b.appendUndefined(name);
break;
default:
qCritical() << "toBson() failed to convert" << obj << "for" << name << "with type" << v.typeName();
ok = false;
}
Q_ASSERT(ok);
++it;
}
return b.obj();
}