int main() { try { cout << "connecting to localhost..." << endl; DBClientConnection c; c.connect("localhost"); cout << "connected ok" << endl; unsigned long long count = c.count("test.foo"); cout << "count of exiting documents in collection test.foo : " << count << endl; bo o = BSON( "hello" << "world" ); c.insert("test.foo", o); string e = c.getLastError(); if( !e.empty() ) { cout << "insert #1 failed: " << e << endl; } // make an index with a unique key constraint c.ensureIndex("test.foo", BSON("hello"<<1), /*unique*/true); c.insert("test.foo", o); // will cause a dup key error on "hello" field cout << "we expect a dup key error here:" << endl; cout << " " << c.getLastErrorDetailed().toString() << endl; } catch(DBException& e) { cout << "caught DBException " << e.toString() << endl; return 1; } return 0; }
void writeJobAd(ClassAd* ad) { clock_t start, end; double elapsed; ExprTree *expr; const char *name; ad->ResetExpr(); BSONObjBuilder b; start = clock(); while (ad->NextExpr(name,expr)) { b.append(name,ExprTreeToString(expr)); } try { c.insert(db_name, b.obj()); } catch(DBException& e) { cout << "caught DBException " << e.toString() << endl; } end = clock(); elapsed = ((float) (end - start)) / CLOCKS_PER_SEC; std:string last_err = c.getLastError(); if (!last_err.empty()) { printf("getLastError: %s\n",last_err.c_str()); } printf("Time elapsed: %1.9f sec\n",elapsed); }
int main() { try { cout << "connecting to localhost..." << endl; DBClientConnection c; c.connect("localhost"); cout << "connected ok" << endl; bo o = BSON( "hello" << "world" ); cout << "inserting..." << endl; time_t start = time(0); for( unsigned i = 0; i < 1000000; i++ ) { c.insert("test.foo", o); } // wait until all operations applied cout << "getlasterror returns: \"" << c.getLastError() << '"' << endl; time_t done = time(0); time_t dt = done-start; cout << dt << " seconds " << 1000000/dt << " per second" << endl; } catch(DBException& e) { cout << "caught DBException " << e.toString() << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
int em_mongodb::setvalue(std::string dbcoll,mongo::Query cond,BSONObj valObj,bool flag) { int ret = MDB_FAIL_SET; DBClientConnection* pconn = getConn(); if(!pconn) return ret; pconn->update(dbcoll,cond,valObj,flag); std::string errmsg = pconn->getLastError(); std::cout << "em_mongodb::setvalue: " << errmsg << std::endl; if(errmsg.empty()) ret = MDB_RET_SUCCESS; boost::mutex::scoped_lock lock(m_iomux); m_connpool[pconn] = false; sem_post(&m_jobsem); return ret; }
int main( int argc, const char **argv ) { const char *port = "27017"; if ( argc != 1 ) { if ( argc != 3 ) throw -12; port = argv[ 2 ]; } DBClientConnection conn; string errmsg; if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { cout << "couldn't connect : " << errmsg << endl; throw -11; } const char * ns = "test.test1"; conn.dropCollection(ns); // clean up old data from any previous tests conn.remove( ns, BSONObj() ); assert( conn.findOne( ns , BSONObj() ).isEmpty() ); // test insert conn.insert( ns ,BSON( "name" << "eliot" << "num" << 1 ) ); assert( ! conn.findOne( ns , BSONObj() ).isEmpty() ); // test remove conn.remove( ns, BSONObj() ); assert( conn.findOne( ns , BSONObj() ).isEmpty() ); // insert, findOne testing conn.insert( ns , BSON( "name" << "eliot" << "num" << 1 ) ); { BSONObj res = conn.findOne( ns , BSONObj() ); assert( strstr( res.getStringField( "name" ) , "eliot" ) ); assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); assert( 1 == res.getIntField( "num" ) ); } // cursor conn.insert( ns ,BSON( "name" << "sara" << "num" << 2 ) ); { auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() ); int count = 0; while ( cursor->more() ) { count++; BSONObj obj = cursor->next(); } assert( count == 2 ); } { auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 1 ) ); int count = 0; while ( cursor->more() ) { count++; BSONObj obj = cursor->next(); } assert( count == 1 ); } { auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 3 ) ); int count = 0; while ( cursor->more() ) { count++; BSONObj obj = cursor->next(); } assert( count == 0 ); } // update { BSONObj res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); BSONObj after = BSONObjBuilder().appendElements( res ).append( "name2" , "h" ).obj(); conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after ); res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); assert( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() ); conn.update( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() , after ); res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); assert( strstr( res.getStringField( "name" ) , "eliot" ) ); assert( strstr( res.getStringField( "name2" ) , "h" ) ); assert( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() ); // upsert conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after , 1 ); assert( ! conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ).isEmpty() ); } { // ensure index assert( conn.ensureIndex( ns , BSON( "name" << 1 ) ) ); assert( ! conn.ensureIndex( ns , BSON( "name" << 1 ) ) ); } { // hint related tests assert( conn.findOne(ns, "{}")["name"].str() == "sara" ); assert( conn.findOne(ns, "{ name : 'eliot' }")["name"].str() == "eliot" ); assert( conn.getLastError() == "" ); // nonexistent index test bool asserted = false; try { conn.findOne(ns, Query("{name:\"eliot\"}").hint("{foo:1}")); } catch ( ... ){ asserted = true; } assert( asserted ); //existing index assert( conn.findOne(ns, Query("{name:'eliot'}").hint("{name:1}")).hasElement("name") ); // run validate assert( conn.validate( ns ) ); } { // timestamp test const char * tsns = "test.tstest1"; conn.dropCollection( tsns ); { mongo::BSONObjBuilder b; b.appendTimestamp( "ts" ); conn.insert( tsns , b.obj() ); } mongo::BSONObj out = conn.findOne( tsns , mongo::BSONObj() ); Date_t oldTime = out["ts"].timestampTime(); unsigned int oldInc = out["ts"].timestampInc(); { mongo::BSONObjBuilder b1; b1.append( out["_id"] ); mongo::BSONObjBuilder b2; b2.append( out["_id"] ); b2.appendTimestamp( "ts" ); conn.update( tsns , b1.obj() , b2.obj() ); } BSONObj found = conn.findOne( tsns , mongo::BSONObj() ); cout << "old: " << out << "\nnew: " << found << endl; assert( ( oldTime < found["ts"].timestampTime() ) || ( oldTime == found["ts"].timestampTime() && oldInc < found["ts"].timestampInc() ) ); } { // check that killcursors doesn't affect last error assert( conn.getLastError().empty() ); BufBuilder b; b.appendNum( (int)0 ); // reserved b.appendNum( (int)-1 ); // invalid # of cursors triggers exception b.appendNum( (int)-1 ); // bogus cursor id Message m; m.setData( dbKillCursors, b.buf(), b.len() ); // say() is protected in DBClientConnection, so get superclass static_cast< DBConnector* >( &conn )->say( m ); assert( conn.getLastError().empty() ); } { list<string> l = conn.getDatabaseNames(); for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ){ cout << "db name : " << *i << endl; } l = conn.getCollectionNames( "test" ); for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ){ cout << "coll name : " << *i << endl; } } cout << "client test finished!" << endl; }
int main(int argc, char *argv[]) { try { cout << "mongoperf" << endl; if( argc > 1 ) { cout << "\n" "usage:\n" "\n" " mongoperf < myjsonconfigfile\n" "\n" " {\n" " nThreads:<n>, // number of threads\n" " fileSizeMB:<n>, // test file size\n" " sleepMicros:<n>, // pause for sleepMicros/nThreads between each operation\n" " mmf:<bool>, // if true do i/o's via memory mapped files\n" " r:<bool>, // do reads\n" " w:<bool> // do writes\n" " }\n" "\n" "most fields are optional.\n" "non-mmf io is direct io (no caching). use a large file size to test making the heads\n" " move significantly and to avoid i/o coalescing\n" "mmf io uses caching (the file system cache).\n" "\n" << endl; return 0; } cout << "use -h for help" << endl; char input[1024]; memset(input, 0, sizeof(input)); cin.read(input, 1000); if( *input == 0 ) { cout << "error no options found on stdin for mongoperf" << endl; return 2; } string s = input; str::stripTrailing(s, "\n\r\0x1a"); try { options = fromjson(s); } catch(...) { cout << s << endl; cout << "couldn't parse json options" << endl; return -1; } cout << "options:\n" << options.toString() << endl; go(); #if 0 cout << "connecting to localhost..." << endl; DBClientConnection c; c.connect("localhost"); cout << "connected ok" << endl; unsigned long long count = c.count("test.foo"); cout << "count of exiting documents in collection test.foo : " << count << endl; bo o = BSON( "hello" << "world" ); c.insert("test.foo", o); string e = c.getLastError(); if( !e.empty() ) { cout << "insert #1 failed: " << e << endl; } // make an index with a unique key constraint c.ensureIndex("test.foo", BSON("hello"<<1), /*unique*/true); c.insert("test.foo", o); // will cause a dup key error on "hello" field cout << "we expect a dup key error here:" << endl; cout << " " << c.getLastErrorDetailed().toString() << endl; #endif } catch(DBException& e) { cout << "caught DBException " << e.toString() << endl; return 1; } return 0; }
int main(int argc, char* argv[]) { Status status = client::initialize(); if ( !status.isOK() ) { std::cout << "failed to initialize the mongo client driver: " << status.toString() << endl; return EXIT_FAILURE; } const char *port = "27017"; try { cout << "connecting to localhost..." << endl; DBConnection.connect(string("localhost:") + port); cout << "connected ok" << endl; string tracePath; const char* defaultTracePath = "/home/vladimir/Desktop/vlad-trace/traces.otf2"; //const char* defaultTracePath = "/home/vladimir/Dicertation/otf2_trace/traces.otf2"; //const char* defaultTracePath = "/home/vladimir/Desktop/qgen10-trace/traces.otf2"; //const char* defaultTracePath = "/home/vladimir/tests/mpi_isend/scorep-20150416_1732_2789913328919/traces.otf2"; if (argc != 2) tracePath = defaultTracePath; else { ifstream in; in.open(argv[1], ios::in); in >> tracePath; in.close(); } OTF2_Reader* reader = OTF2_Reader_Open(tracePath.c_str()); uint64_t tid_temp = 0; OTF2_Reader_GetTraceId (reader, &tid_temp); // get procs number TODO uint64_t numProcesses = 0; OTF2_Reader_GetNumberOfLocations(reader, &numProcesses); if ( numProcesses == 0 ) { std::cout << "Something wrong with processes number" << endl; return EXIT_FAILURE; } NumProcesses = numProcesses; BeginTimes = new uint64_t[numProcesses]; for(int i = 0; i < numProcesses; i++){ BeginTimes[i] = 0; } // SendTo = new int[numProcesses]; //for(int i = 0; i < numProcesses; i++){ // SendTo[i] = -1; //} SendLength = new long long int[numProcesses]; for(int i = 0; i < numProcesses; i++){ SendLength[i] = 0; } //RecvFrom = new int[numProcesses]; //for(int i = 0; i < numProcesses; i++){ // RecvFrom[i] = -1; //} RecvLength = new long long int[numProcesses]; for(int i = 0; i < numProcesses; i++){ RecvLength[i] = 0; } Root = new int[numProcesses]; for(int i = 0; i < numProcesses; i++){ Root[i] = -1; } RegionNames = new int[numProcesses]; for(int i = 0; i < numProcesses; i++){ RegionNames[i] = -1; } IsPointEvent = new bool[numProcesses]; for(int i = 0; i < numProcesses; i++){ IsPointEvent[i] = 0; } IsCommEvent = new bool[numProcesses]; for(int i = 0; i < numProcesses; i++){ IsCommEvent[i] = 0; } //Point_SendTime = new long long int[numProcesses * numProcesses]; //for(int i = 0; i < numProcesses * numProcesses; i++){ // Point_SendTime[i] = -1; //} //Point_SendTime = new long long int[numProcesses * numProcesses]; for(int i = 0; i < numProcesses * numProcesses; i++){ //Point_SendTime[i] = -1; Point_SendTime.push_back(vector<long long int>()); } for(int i = 0; i < numProcesses * numProcesses; i++){ //Point_SendTime[i] = -1; Point_SendComm.push_back(vector<int>()); } for(int i = 0; i < numProcesses * numProcesses; i++){ //Point_SendTime[i] = -1; Point_SendTag.push_back(vector<int>()); } for(int i = 0; i < numProcesses * numProcesses; i++){ //Point_SendTime[i] = -1; Point_SendLength.push_back(vector<long long int>()); } cout << tid_temp << endl; char *buff; buff = (char*) malloc (64); sprintf(buff , "%" PRIx64, tid_temp); TraceId = string(buff); free(buff); auto_ptr<DBClientCursor> cursor = DBConnection.query("Otf2Data.TraceIds", Query("{TraceId: \"" + TraceId + "\", Status: \"done\"}")); if(cursor->more()){ cout << "Трасса с таким id уже сществует в БД" << endl; } else{ DBConnection.remove("Otf2Data.Events", Query("{TraceId: \"" + TraceId + "\"}")); DBConnection.remove("Otf2Data.PointOperations", Query("{TraceId: \"" + TraceId + "\"}")); OTF2_GlobalDefReader* global_def_reader = OTF2_Reader_GetGlobalDefReader(reader); // creating global definition callbacks handle OTF2_GlobalDefReaderCallbacks* global_def_callbacks = OTF2_GlobalDefReaderCallbacks_New(); // setting global definition reader callbacks to handle // получаем все строки OTF2_GlobalDefReaderCallbacks_SetStringCallback( global_def_callbacks, print_global_def_string ); // получаем названия регионов OTF2_GlobalDefReaderCallbacks_SetRegionCallback( global_def_callbacks, print_global_def_region ); OTF2_GlobalDefReaderCallbacks_SetLocationCallback(global_def_callbacks, &GlobDefLocation_Register); //OTF2_GlobalDefReaderCallbacks_SetCommCallback (global_def_callbacks, &GlobDefCommunicator_Register); //OTF2_GlobalDefReaderCallbacks_SetGroupCallback(global_def_callbacks, &GlobDefGroup_Register); // registering callbacks and deleting callbacks handle OTF2_Reader_RegisterGlobalDefCallbacks(reader, global_def_reader, global_def_callbacks, reader); OTF2_GlobalDefReaderCallbacks_Delete( global_def_callbacks ); // reading all global definitions uint64_t definitions_read = 0; OTF2_Reader_ReadAllGlobalDefinitions( reader, global_def_reader, &definitions_read ); printf("Definitions_read = %"PRIu64"\n", definitions_read); // DEFINITIONS READING END cout << "numProcesses = " << numProcesses << endl; // EVENTS READING START OTF2_GlobalEvtReader* global_evt_reader = OTF2_Reader_GetGlobalEvtReader(reader); // creating global event callbacks handle OTF2_GlobalEvtReaderCallbacks* event_callbacks = OTF2_GlobalEvtReaderCallbacks_New(); // setting global event reader callbacks to handle OTF2_GlobalEvtReaderCallbacks_SetEnterCallback( event_callbacks, &EnterCallback); OTF2_GlobalEvtReaderCallbacks_SetLeaveCallback( event_callbacks, &LeaveCallback); OTF2_GlobalEvtReaderCallbacks_SetMpiSendCallback(event_callbacks, &MPI_Send_print); OTF2_GlobalEvtReaderCallbacks_SetMpiIsendCallback(event_callbacks, &MPI_Isend_print); OTF2_GlobalEvtReaderCallbacks_SetMpiRecvCallback(event_callbacks, &MPI_Recv_print); OTF2_GlobalEvtReaderCallbacks_SetMpiIrecvCallback(event_callbacks, &MPI_Irecv_print); //OTF2_GlobalEvtReaderCallbacks_SetMpiCollectiveBeginCallback(event_callbacks, &MPI_CollectiveBegin_print); OTF2_GlobalEvtReaderCallbacks_SetMpiCollectiveEndCallback(event_callbacks, &MPI_CollectiveEnd_print); // registering callbacks and deleting callbacks handle OTF2_Reader_RegisterGlobalEvtCallbacks(reader, global_evt_reader, event_callbacks, NULL); OTF2_GlobalEvtReaderCallbacks_Delete(event_callbacks); // reading all global events uint64_t events_read = 0; OTF2_Reader_ReadAllGlobalEvents(reader, global_evt_reader, &events_read); //printf("Events_read = %"PRIu64"\n", events_read); OTF2_Reader_Close( reader ); cout << "Events started at " << startTime << endl; cout << "Events ended at " << endTime << endl; long long int num1 = numProcesses; DBConnection.insert("Otf2Data.TraceIds", BSON( "TraceId" << TraceId << "Status" << "done" << "NumberOfLocations" << num1)); cout << "getlasterror returns: \"" << DBConnection.getLastError() << '"' << endl; cout << "Inserting successfully done! " << endl; } delete [] BeginTimes; delete [] IsPointEvent; delete [] IsCommEvent; delete [] RegionNames; //delete [] SendTo; //delete [] RecvFrom; delete [] SendLength; delete [] RecvLength; delete [] Root; //delete [] Point_SendTime; //delete [] Point_SendComm; //delete [] Point_SendTag; //delete [] Point_SendLength; } catch(DBException& e) { cout << "caught DBException " << e.toString() << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
void run(string router, string ns, long long start, long long range, int sleepTime) { DBClientConnection c; c.connect(router); c.setWriteConcern(W_NORMAL); struct timeval start_time, stop_time, delay; char timeStr[25]; bool flag; BSONObj b; srand(time(NULL)); long long user_id = -1; long long number = -1; int opSelector; string s; BSONObj insertObj; BSONObj query; BSONObj updateObj; BSONObj readObj; int numOps = 3; int i = 0; string operation = "none"; map<long long, int> insertedKeys; while( true ) { flag = false; curTimeString(timeStr); gettimeofday(&start_time, NULL); opSelector = i % numOps; i++; try { switch(opSelector) { case 0: //insert operation = "insert"; while(true) { user_id = start + (rand() % range); if( insertedKeys.find(user_id) == insertedKeys.end()) { //key not been inserted previously insertedKeys.insert(make_pair(user_id, 1)); cout<<operation<<": Info: inserting " << user_id << endl; break; } } //insert command goes here number = 2 * start + range - user_id; insertObj = BSON("user_id" << user_id << "number" << number << "name" << "name"); //cout<<"insert: "<<insertObj.toString()<<endl; c.insert(ns, insertObj); s = c.getLastError(ns, false, false, 1, 0); if (s.length() > 0) { flag = true; cout << "Error:" << s << endl; } break; case 1: //update operation = "update"; //update command goes here query = BSON("user_id" << user_id); updateObj = BSON("user_id" << user_id << "number" << number << "name" << "nameUpdated"); //cout<<"update: "<<updateObj.toString()<<endl; c.update(ns, Query(query), updateObj); s = c.getLastError(ns, false, false, 1, 0); if (s.length() > 0) { flag = true; cout << "Error:" << s << endl; } break; case 2: //read operation = "read"; readObj = BSON("user_id" << user_id); //cout<<"read: "<<readObj.toString()<<endl; b = c.findOne(ns, Query(readObj), 0, QueryOption_SlaveOk); if (b.isEmpty() <= 0) flag = true; s = c.getLastError(ns, false, false, 1, 0); if (s.length() > 0) { flag = true; cout << "Error:" << s << endl; } break; default: cout<<"Unrecognized opSelector ! " << opSelector << endl; cout<<"i : " << i << " numOps : " << numOps << endl; break; } } catch (DBException e){ flag = true; cout << "Error: " << e.toString() << endl; } if (!flag) { gettimeofday(&stop_time, NULL); if (opSelector == 2) cout << "Returned result:" << b.toString() << endl; delay = subtract(start_time, stop_time); cout<<operation<<": "; cout << timeStr << ": " << delay.tv_sec*1000 + delay.tv_usec/(double)1000 << endl; } else { cout<<operation<<": "; cout << timeStr << ": -100" << endl; } usleep(sleepTime); } }
int main( int argc, const char **argv ) { const char *port = "27017"; if ( argc != 1 ) { if ( argc != 3 ) { std::cout << "need to pass port as second param" << endl; return EXIT_FAILURE; } port = argv[ 2 ]; } DBClientConnection conn; string errmsg; if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { cout << "couldn't connect : " << errmsg << endl; return EXIT_FAILURE; } const char * ns = "test.test1"; conn.dropCollection(ns); // clean up old data from any previous tests conn.remove( ns, BSONObj() ); verify( conn.findOne( ns , BSONObj() ).isEmpty() ); // test insert conn.insert( ns ,BSON( "name" << "eliot" << "num" << 1 ) ); verify( ! conn.findOne( ns , BSONObj() ).isEmpty() ); // test remove conn.remove( ns, BSONObj() ); verify( conn.findOne( ns , BSONObj() ).isEmpty() ); // insert, findOne testing conn.insert( ns , BSON( "name" << "eliot" << "num" << 1 ) ); { BSONObj res = conn.findOne( ns , BSONObj() ); verify( strstr( res.getStringField( "name" ) , "eliot" ) ); verify( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); verify( 1 == res.getIntField( "num" ) ); } // cursor conn.insert( ns ,BSON( "name" << "sara" << "num" << 2 ) ); { auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() ); int count = 0; while ( cursor->more() ) { count++; BSONObj obj = cursor->next(); } verify( count == 2 ); } { auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 1 ) ); int count = 0; while ( cursor->more() ) { count++; BSONObj obj = cursor->next(); } verify( count == 1 ); } { auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 3 ) ); int count = 0; while ( cursor->more() ) { count++; BSONObj obj = cursor->next(); } verify( count == 0 ); } // update { BSONObj res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); verify( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); BSONObj after = BSONObjBuilder().appendElements( res ).append( "name2" , "h" ).obj(); conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after ); res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); verify( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); verify( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() ); conn.update( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() , after ); res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); verify( strstr( res.getStringField( "name" ) , "eliot" ) ); verify( strstr( res.getStringField( "name2" ) , "h" ) ); verify( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() ); // upsert conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after , 1 ); verify( ! conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ).isEmpty() ); } { // ensure index verify( conn.ensureIndex( ns , BSON( "name" << 1 ) ) ); verify( ! conn.ensureIndex( ns , BSON( "name" << 1 ) ) ); } { // 5 second TTL index const char * ttlns = "test.ttltest1"; conn.dropCollection( ttlns ); { mongo::BSONObjBuilder b; b.appendTimeT("ttltime", time(0)); b.append("name", "foo"); conn.insert(ttlns, b.obj()); } conn.ensureIndex(ttlns, BSON("ttltime" << 1), false, false, "", true, false, -1, 5); verify(!conn.findOne(ttlns, BSONObjBuilder().append("name", "foo").obj()).isEmpty()); // Sleep 66 seconds, 60 seconds for the TTL loop, 5 seconds for the TTL and 1 to ensure sleepsecs(66); verify(conn.findOne(ttlns, BSONObjBuilder().append("name", "foo").obj()).isEmpty()); } { // hint related tests // tokumx doesn't reorder documents just because you updated one, what even is that verify( conn.findOne(ns, "{}")["name"].str() == "eliot" ); verify( conn.findOne(ns, "{ name : 'sara' }")["name"].str() == "sara" ); verify( conn.getLastError() == "" ); // nonexistent index test bool asserted = false; try { conn.findOne(ns, Query("{name:\"eliot\"}").hint("{foo:1}")); } catch ( ... ) { asserted = true; } verify( asserted ); //existing index verify( conn.findOne(ns, Query("{name:'eliot'}").hint("{name:1}")).hasElement("name") ); // run validate verify( conn.validate( ns ) ); } { // timestamp test const char * tsns = "test.tstest1"; conn.dropCollection( tsns ); { mongo::BSONObjBuilder b; b.appendTimestamp( "ts" ); conn.insert( tsns , b.obj() ); } mongo::BSONObj out = conn.findOne( tsns , mongo::BSONObj() ); Date_t oldTime = out["ts"].timestampTime(); unsigned int oldInc = out["ts"].timestampInc(); { mongo::BSONObjBuilder b1; b1.append( out["_id"] ); mongo::BSONObjBuilder b2; b2.append( out["_id"] ); b2.appendTimestamp( "ts" ); conn.update( tsns , b1.obj() , b2.obj() ); } BSONObj found = conn.findOne( tsns , mongo::BSONObj() ); cout << "old: " << out << "\nnew: " << found << endl; verify( ( oldTime < found["ts"].timestampTime() ) || ( oldTime == found["ts"].timestampTime() && oldInc < found["ts"].timestampInc() ) ); } { // check that killcursors doesn't affect last error verify( conn.getLastError().empty() ); BufBuilder b; b.appendNum( (int)0 ); // reserved b.appendNum( (int)-1 ); // invalid # of cursors triggers exception b.appendNum( (int)-1 ); // bogus cursor id Message m; m.setData( dbKillCursors, b.buf(), b.len() ); // say() is protected in DBClientConnection, so get superclass static_cast< DBConnector* >( &conn )->say( m ); verify( conn.getLastError().empty() ); } { list<string> l = conn.getDatabaseNames(); for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ) { cout << "db name : " << *i << endl; } l = conn.getCollectionNames( "test" ); for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ) { cout << "coll name : " << *i << endl; } } { //Map Reduce (this mostly just tests that it compiles with all output types) const string ns = "test.mr"; conn.insert(ns, BSON("a" << 1)); conn.insert(ns, BSON("a" << 1)); const char* map = "function() { emit(this.a, 1); }"; const char* reduce = "function(key, values) { return Array.sum(values); }"; const string outcoll = ns + ".out"; BSONObj out; out = conn.mapreduce(ns, map, reduce, BSONObj()); // default to inline //MONGO_PRINT(out); out = conn.mapreduce(ns, map, reduce, BSONObj(), outcoll); //MONGO_PRINT(out); out = conn.mapreduce(ns, map, reduce, BSONObj(), outcoll.c_str()); //MONGO_PRINT(out); out = conn.mapreduce(ns, map, reduce, BSONObj(), BSON("reduce" << outcoll)); //MONGO_PRINT(out); } { // test timeouts DBClientConnection conn( true , 0 , 2 ); if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { cout << "couldn't connect : " << errmsg << endl; throw -11; } conn.insert( "test.totest" , BSON( "x" << 1 ) ); BSONObj res; bool gotError = false; verify( conn.eval( "test" , "return db.totest.findOne().x" , res ) ); try { conn.eval( "test" , "sleep(5000); return db.totest.findOne().x" , res ); } catch ( std::exception& e ) { gotError = true; log() << e.what() << endl; } verify( gotError ); // sleep so the server isn't locked anymore sleepsecs( 4 ); verify( conn.eval( "test" , "return db.totest.findOne().x" , res ) ); } cout << "client test finished!" << endl; return EXIT_SUCCESS; }