BSONObj* DjondbConnection::findByKey(const char* db, const char* ns, const char* select, const char* id) { if (_logger->isDebug()) _logger->debug("executing findByKey db: %s, ns: %s, select: %s, id: %s", db, ns, select, id); if (!isOpen()) { throw DjondbException(D_ERROR_CONNECTION, "Not connected to any server"); } std::string filter = format("$'_id' == '%s'", id); BSONArrayObj* result = find(const_cast<char*>(db), const_cast<char*>(ns), const_cast<char*>(select), const_cast<char*>(filter.c_str())); BSONObj* res = NULL; if (result->length() == 1) { if (_logger->isDebug()) _logger->debug(2, "findByKey found 1 result"); res = *result->begin(); } else { if (result->length() > 1) { throw DjondbException(D_ERROR_TOO_MANY_RESULTS, "The result contains more than 1 result"); } } BSONObj* bsonresult = NULL; if (res != NULL) { // creates a copy of the result before deleting the temporal objects bsonresult = new BSONObj(*res); } delete result; return bsonresult; }
void testParserArray() { cout << "testParserArray" << endl; BSONArrayObj* array = BSONParser::parseArray("[{age: 1, name: 'John', salary: 3500.25, rel1: {innertext: 'inner text'}}, {age: 2, name: 'John2', salary: 23500.25, rel1: {innertext: 'inner text2'}}]"); TEST_ASSERT(array != NULL); TEST_ASSERT(array->length() == 2); BSONObj* obj = array->get(0); TEST_ASSERT(obj != NULL); TEST_ASSERT(obj->has("age")); TEST_ASSERT(obj->getInt("age") == 1); TEST_ASSERT(obj->has("name")); TEST_ASSERT(strcmp(obj->getString("name"), "John") == 0); TEST_ASSERT(obj->has("salary")); TEST_ASSERT(obj->getDouble("salary") == 3500.25); TEST_ASSERT(obj->getBSON("rel1") != NULL); TEST_ASSERT(strcmp(obj->getBSON("rel1")->getString("innertext"), "inner text") == 0); BSONArrayObj::iterator i = array->begin(); TEST_ASSERT(i != array->end()); delete array; }
void testTransaction() { printf("%s\n", "testTransaction"); DummyController* controller = new DummyController(); BaseTransaction* tx = new BaseTransaction(controller); tx->dropNamespace("db", "txns"); BSONObj o; std::string* id = uuid(); o.add("_id", const_cast<char*>(id->c_str())); o.add("name", "John"); tx->insert("db", "txns", &o); BSONArrayObj* res = tx->find("db", "txns", "*", ""); TEST_ASSERT(res->length() == 1); BSONObj* test1 = *res->begin(); TEST_ASSERT(test1->getString("name").compare("John") == 0); test1->add("name", "Peter"); tx->update("db", "txns", test1); delete res; res = tx->find("db", "txns", "*", ""); TEST_ASSERT(res->length() == 1); BSONObj* test2 = *res->begin(); TEST_ASSERT(test2->getString("name").compare("Peter") == 0); delete res; printf("%s\n", "Deleting tx"); delete tx; delete controller; delete id; printf("%s\n", "~testTransaction"); }