void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; ssKey >> acentry.nEntryNo; entries.push_back(acentry); } pcursor->close(); }
void CWalletDB::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = batch.GetCursor(); if (!pcursor) throw std::runtime_error(std::string(__func__) + ": cannot create DB cursor"); bool setRange = true; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (setRange) ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? std::string("") : strAccount), uint64_t(0))); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = batch.ReadAtCursor(pcursor, ssKey, ssValue, setRange); setRange = false; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw std::runtime_error(std::string(__func__) + ": error scanning DB"); } // Unserialize std::string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; ssKey >> acentry.nEntryNo; entries.push_back(acentry); } pcursor->close(); }
bool DatabaseManager::recordRangeExists(const StringPimpl &key) { //Go through the range of the existence keys and //add them to the list Dbc *cursor = NULL; try { Dbt dbKey((void *)key.c_str(), key.size() + 1); Dbt dbData; m_pimpl->checkTSSInit(); m_pimpl->m_database->cursor(&(**m_pimpl->m_transaction), &cursor, m_pimpl->m_cursorFlags); int ret = cursor->get(&dbKey, &dbData, DB_SET_RANGE); while(ret != DB_NOTFOUND) { StringPimpl dataString = StringPimpl((char *) dbData.get_data()); StringPimpl keyString = StringPimpl((char *) dbKey.get_data()); if(!keyString.startsWith(key) || keyString == key) { //We are at the end of the range break; } else { cursor->close(); return true; } } cursor->close(); return false; } catch (DbException &e) { std::cerr << "Error in deleteRecordRange: " << e.what() << e.get_errno() << std::endl; if(cursor != NULL) { cursor->close(); } return false; } }
void CWalletDB::ListPubCoin(std::list<CZerocoinEntry>& listPubCoin) { Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListPubCoin() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; loop { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << make_pair(string("zerocoin"), CBigNum(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListPubCoin() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "zerocoin") break; CBigNum value; ssKey >> value; CZerocoinEntry zerocoinItem; ssValue >> zerocoinItem; listPubCoin.push_back(zerocoinItem); } pcursor->close(); }
uint32_t bdb_common::find_last_block_depth(txn_guard_ptr txn) { Dbc* cursor; db_blocks_->cursor(txn->get(), &cursor, 0); BITCOIN_ASSERT(cursor != nullptr); writable_data_type key, data; if (cursor->get(key.get(), data.get(), DB_LAST) == DB_NOTFOUND) return std::numeric_limits<uint32_t>::max(); BITCOIN_ASSERT(key.get()->get_size() == 4); uint32_t last_block_depth = cast_chunk<uint32_t>(key.data()); cursor->close(); return last_block_depth; }
// Display all the stock quote information in the database. int RepMgrGSG::print_stocks(Db *dbp) { Dbc *dbc; Dbt key, data; #define MAXKEYSIZE 10 #define MAXDATASIZE 20 char keybuf[MAXKEYSIZE + 1], databuf[MAXDATASIZE + 1]; int ret, t_ret; u_int32_t keysize, datasize; if ((ret = dbp->cursor(NULL, &dbc, 0)) != 0) { dbp->err(ret, "can't open cursor"); return (ret); } memset(&key, 0, sizeof(key)); memset(&data, 0, sizeof(data)); cout << "\tSymbol\tPrice" << endl << "\t======\t=====" << endl; for (ret = dbc->get(&key, &data, DB_FIRST); ret == 0; ret = dbc->get(&key, &data, DB_NEXT)) { keysize = key.get_size() > MAXKEYSIZE ? MAXKEYSIZE : key.get_size(); memcpy(keybuf, key.get_data(), keysize); keybuf[keysize] = '\0'; datasize = data.get_size() >= MAXDATASIZE ? MAXDATASIZE : data.get_size(); memcpy(databuf, data.get_data(), datasize); databuf[datasize] = '\0'; cout << "\t" << keybuf << "\t" << databuf << endl; } cout << endl << flush; if ((t_ret = dbc->close()) != 0 && ret == 0) { cout << "closed cursor" << endl; ret = t_ret; } switch (ret) { case 0: case DB_NOTFOUND: case DB_LOCK_DEADLOCK: return (0); default: return (ret); } }
vector<string> Freeze::EvictorIBase::allDbs() const { vector<string> result; try { Db db(_dbEnv->getEnv(), 0); db.open(0, Ice::nativeToUTF8(_communicator, _filename).c_str(), 0, DB_UNKNOWN, DB_RDONLY, 0); Dbc* dbc = 0; db.cursor(0, &dbc, 0); Dbt dbKey; dbKey.set_flags(DB_DBT_MALLOC); Dbt dbValue; dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); bool more = true; while(more) { more = (dbc->get(&dbKey, &dbValue, DB_NEXT) == 0); if(more) { string dbName(static_cast<char*>(dbKey.get_data()), dbKey.get_size()); if(dbName.find(indexPrefix) != 0) { result.push_back(dbName); } free(dbKey.get_data()); } } dbc->close(); db.close(0); } catch(const DbException& dx) { if(dx.get_errno() != ENOENT) { DatabaseException ex(__FILE__, __LINE__); ex.message = dx.what(); throw ex; } } return result; }
bool Table::Visit(TableVisitor &tv) { if (!tv.IsForward()) return VisitBackward(tv); ByteString bsKey, bsValue; Dbc* cursor = NULL; bool ret = true; u_int32_t flags = DB_NEXT; // TODO call tv.OnComplete() or error handling if (db->cursor(NULL, &cursor, 0) != 0) return false; Dbt key, value; if (tv.GetStartKey() && tv.GetStartKey()->length > 0) { key.set_data(tv.GetStartKey()->buffer); key.set_size(tv.GetStartKey()->length); flags = DB_SET_RANGE; } while (cursor->get(&key, &value, flags) == 0) { bsKey.size = key.get_size(); bsKey.length = key.get_size(); bsKey.buffer = (char*) key.get_data(); bsValue.size = value.get_size(); bsValue.length = value.get_size(); bsValue.buffer = (char*) value.get_data(); ret = tv.Accept(bsKey, bsValue); if (!ret) break; if (bsKey.length > 2 && bsKey.buffer[0] == '@' && bsKey.buffer[1] == '@') { key.set_data((void*)"@@~"); key.set_size(3); flags = DB_SET_RANGE; } else flags = DB_NEXT; } cursor->close(); tv.OnComplete(); return ret; }
//------------------------------------------------------------------------------------------------- unsigned BDBPersister::get(const unsigned from, const unsigned to, Session& session, bool (Session::*callback)(const Session::SequencePair& with, Session::RetransmissionContext& rctx)) const { unsigned last_seq(0); get_last_seqnum(last_seq); unsigned recs_sent(0), startSeqNum(find_nearest_highest_seqnum (from, last_seq)); const unsigned finish(to == 0 ? last_seq : to); Session::RetransmissionContext rctx(from, to, session.get_next_send_seq()); if (!startSeqNum || from > finish) { GlobalLogger::log("No records found"); rctx._no_more_records = true; (session.*callback)(Session::SequencePair(0, ""), rctx); return 0; } KeyDataBuffer buffer(startSeqNum); KeyDataPair keyPair(buffer); Dbc *cursorp; _db->cursor (0, &cursorp, 0); int retval; if ((retval = cursorp->get(&keyPair._key, &keyPair._data, DB_SET)) == 0) { do { const unsigned seqnum(buffer.keyBuf_.int_); if (!seqnum || seqnum > finish) break; Session::SequencePair result(seqnum, buffer.dataBuf_); ++recs_sent; if (!(session.*callback)(result, rctx)) break; } while(cursorp->get(&keyPair._key, &keyPair._data, DB_NEXT) == 0); rctx._no_more_records = true; (session.*callback)(Session::SequencePair(0, ""), rctx); } else { ostringstream ostr; ostr << "record not found (" << db_strerror(retval) << ')'; GlobalLogger::log(ostr.str()); } cursorp->close(); return recs_sent; }
void DatabaseManager::deleteRecordRange(const StringPimpl &key) { Dbc *cursor = NULL; try { Dbt dbKey((void *)key.c_str(), key.size() + 1); Dbt dbData; m_pimpl->checkTSSInit(); m_pimpl->m_database->cursor(&(**m_pimpl->m_transaction), &cursor, m_pimpl->m_cursorFlags); int ret = cursor->get(&dbKey, &dbData, DB_SET_RANGE); while(ret != DB_NOTFOUND) { StringPimpl dataString = StringPimpl((char *) dbData.get_data()); StringPimpl keyString = StringPimpl((char *) dbKey.get_data()); if(!keyString.startsWith(key)) { //We are at the end of the range break; } cursor->del(0); ret = cursor->get(&dbKey, &dbData, DB_NEXT); } cursor->close(); } catch (DbException &e) { std::cerr << "Error in deleteRecordRange: " << e.what() << e.get_errno() << std::endl; if(cursor != NULL) { cursor->close(); } } }
bool CDBStrMultiMap::get_any( string &key , vector<string> &values ) { if( db_is_open == false ) { cout<<"==== Can not get items from BDB.BDB has not been opened."<<endl; return false; } try{ Dbc *dbcq; db->cursor(NULL, &dbcq, 0); Dbt dbt_key1; Dbt dbt_data1; char* key_str; char* data_str; if( dbcq->get(&dbt_key1, &dbt_data1, DB_FIRST) == 0 ) { key_str = (char*)dbt_key1.get_data(); for( ; key_str< key_str + strlen(key_str) ; key_str++ ) { key += *key_str; } data_str = (char*)dbt_data1.get_data(); values.push_back( data_str ); dbcq->del(0); //Dbt dbt_key2( *key_str , strlen(key_str) ); while( dbcq -> get(&dbt_key1, &dbt_data1, DB_SET) == 0 ) { key_str = (char*)dbt_key1.get_data(); values.push_back( data_str ); dbcq->del(0); } } dbcq->close(); } catch( DbException &e) { cerr<<"!! Exception: "<<e.what()<<endl; return false; } return true; }
void JabberBotSession::RunSession(void) { SetPresence(PresenceStanza::Available); JabberIqRoster rosterQuery; m_session->SendMessage(rosterQuery, false); while(m_continueRunning) { time_t now = time(NULL); while (!m_upcomingQueue.empty() && (now > m_upcomingQueue.top().Next())) { std::ostringstream message; message << "Appending " << m_upcomingQueue.top().User() << " to the list of people who get messages now" << std::endl; syslog(LOG_NOTICE, message.str().c_str()); m_sendList.insert(m_upcomingQueue.top().User()); m_upcomingQueue.pop(); } ProcessSendList(); if (m_eod < now) { time_t bod = m_eod; m_eod += 86400; m_sendList.clear(); while (!m_upcomingQueue.empty()) { m_upcomingQueue.pop(); } Dbc *cursor; m_subscriptionDb.cursor(NULL, &cursor, 0); if (NULL != cursor) { Dbt key, data; m_eod = bod + 86400; while (0 == cursor->get(&key, &data, DB_NEXT)) { std::string user((char *)key.get_data()); time_t t1 = random() % 43200; time_t t2 = random() % 43200; Upcoming newEntry(user, bod + t1 + t2); m_upcomingQueue.push(newEntry); } cursor->close(); } } sleep(1); } }
bool FileRecord::ListLocks(std::list<std::string>& locks) { if(!valid_) return false; Glib::Mutex::Lock lock(lock_); Dbc* cur = NULL; if(db_lock_->cursor(NULL,&cur,0)) return false; for(;;) { Dbt key; Dbt data; if(cur->get(&key,&data,DB_NEXT_NODUP) != 0) break; // TODO: handle errors std::string str; uint32_t size = key.get_size(); parse_string(str,key.get_data(),size); locks.push_back(str); }; cur->close(); return true; }
bool Table::Prune(Transaction* tx, const ByteString &prefix) { Dbc* cursor = NULL; u_int32_t flags = DB_NEXT; DbTxn* txn; if (tx == NULL) txn = NULL; else txn = tx->txn; if (db->cursor(txn, &cursor, 0) != 0) return false; Dbt key, value; if (prefix.length > 0) { key.set_data(prefix.buffer); key.set_size(prefix.length); flags = DB_SET_RANGE; } while (cursor->get(&key, &value, flags) == 0) { if (key.get_size() < prefix.length) break; if (strncmp(prefix.buffer, (char*)key.get_data(), prefix.length) != 0) break; // don't delete keys starting with @@ if (!(key.get_size() >= 2 && ((char*)key.get_data())[0] == '@' && ((char*)key.get_data())[1] == '@')) cursor->del(0); flags = DB_NEXT; } if (cursor) cursor->close(); return true; }
//------------------------------------------------------------------------------------------------- unsigned BDBPersister::get_last_seqnum(unsigned& sequence) const { Dbc *cursorp; _db->cursor (0, &cursorp, 0); KeyDataBuffer buffer; KeyDataPair keyPair(buffer); int retval(cursorp->get(&keyPair._key, &keyPair._data, DB_LAST)); cursorp->close(); if (retval) { ostringstream ostr; ostr << "last record not found (" << db_strerror(retval) << ')'; GlobalLogger::log(ostr.str()); return 0; } return sequence = buffer.keyBuf_.int_; }
void MultiPartHeader::removeServer(Db* pDB, quint16 serverId) { serverPart.remove(serverId); serverLowest.remove(serverId); quint64 multiPartKey = getMultiPartKey(); Header* h = 0; // Walk the headers to get the PartNumMap Dbc *cursorp = 0; // Get a cursor pDB->cursor(NULL, &cursorp, DB_WRITECURSOR); // Set up our DBTs Dbt key(&multiPartKey, sizeof(quint64)); Dbt data; int ret = cursorp->get(&key, &data, DB_SET); while (ret != DB_NOTFOUND) { h = new Header((char*)data.get_data(), (char*)key.get_data()); if (h->isHeldByServer(serverId)) { h->removeServerPartNum(serverId); if (h->isServerNumMapEmpty()) { cursorp->del(0); size-=h->getSize(); missingParts++; } } Q_DELETE(h); ret = cursorp->get(&key, &data, DB_NEXT_DUP); } if (cursorp != NULL) cursorp->close(); }
bool CDBStrMultiMap::get_index( vector<string> &indexvec ) { if( db_is_open == false ) { cout<<"==== Can not get items from BDB.BDB has not been opened."<<endl; return false; } try{ Dbc *dbcp; db->cursor(NULL, &dbcp, 0); Dbt dbt_key1; Dbt dbt_data1; char* key_str; //char* data_str; string key; while( dbcp->get(&dbt_key1, &dbt_data1, DB_NEXT ) ==0 ) { key_str = (char*)dbt_key1.get_data(); //get the key for( ; key_str < key_str + strlen(key_str) ; key_str++ ) { key += *key_str; } if( find( indexvec.begin(), indexvec.end(), key ) == indexvec.end() ){ //if it is not a duplicate key indexvec.push_back( key ); } key.clear(); //dbcp->del(0); } dbcp->close(); } catch( DbException &e) { cerr<<"!! Exception: "<<e.what()<<endl; return false; } return true; }
/* This function is written specially for command line search. * It searches the synonym db using keyStr and nsStr. * If the region name contains keyStr and nsStr EQUALS nsStr, * the region name will be put into the string vector. * Returns 0 if everything is ok, non-zero otherwise. */ int findSynonyms(string dbHome, string dbName, string key_in, bool ik_flag, string ns_in, bool ins_flag, vector <synonymRec> &outputList) { string keyStr = key_in; if (ik_flag) keyStr = toLowerCase(key_in); string nsStr = ns_in; if (ins_flag) nsStr = toLowerCase(ns_in); mydb synonymDB(dbHome, dbName, DB_RDONLY); Dbc *cursorp; Dbt key, data; int ret; int foo = 0; try { synonymDB.getDb().cursor(NULL, &cursorp, 0); while ((ret = cursorp->get(&key, &data, DB_NEXT)) == 0 ) { synonymRec sData(data.get_data()); string sName = sData.getName(); if (ik_flag) sName = toLowerCase(sData.getName()); string nsName = sData.getNameSpace(); if (ins_flag) nsName = toLowerCase(sData.getNameSpace()); if (sName.find(keyStr) != string::npos && nsStr == nsName) outputList.push_back(sData); } } catch(DbException &e) { synonymDB.getDb().err(e.get_errno(), "Error in getAllSynonyms()"); foo = -1; } catch(exception &e) { synonymDB.getDb().errx("Error in getAllSynonyms(): %s", e.what()); foo = -2; } cursorp->close(); return foo; }
vector<string> LoginDB::getKeys() { LoginDB::openDb(); vector<string> keys;// = new vector<string>; Dbc *cursorp; Dbt key, data; //key.set_flags(DB_DBT_USERMEM); // data.set_flags(DB_DBT_USERMEM); // Get a cursor db->cursor(NULL, &cursorp, 0); string name; int ret; // Iterate over the database, retrieving each record in turn. while ((ret = cursorp->get(&key, &data, DB_NEXT)) == 0) { // Do interesting things with the Dbts here. char* tmp = static_cast<char*> (key.get_data()); name.resize(key.get_size()); copy(tmp, tmp+key.get_size(), name.begin()); //name += '\0'; keys.push_back( name); cout<<"name is "<<name<<" --- "<<name.size()<<" --- " <<key.get_size() <<endl; } cursorp->close(); //cout << "Value in DB-> " << name << endl; LoginDB::closeDb(); return keys; }
void printSortedDB() { //std::vector<std::pair<float,std::string> > dbvec; std::vector<dbvecinf> dbvec; using std::cout; unsigned int total_good; unsigned int total_bad; getTotals(total_good, total_bad); Dbc * cur; db.cursor(NULL, &cur, 0); if(cur) { Dbt key, data; while(cur->get(&key, &data, DB_NEXT) == 0) { BayesDBData bdata; int s = data.get_size(); if(s != sizeof(bdata)) throw std::runtime_error("Bayesian DB returned wrong record size"); void * vdata = data.get_data(); memcpy((void *)&bdata, vdata, s); float vand_prob = (float)bdata.bad_edits / (float)total_bad; float good_prob = (float)bdata.good_edits / (float)total_good; float vandalness = vand_prob / (vand_prob + good_prob); std::string word((char *)key.get_data(), key.get_size()); //dbvec.push_back(std::pair<float,std::string>(vandalness, word)); dbvecinf dbvi; dbvi.score = vandalness; dbvi.word = word; dbvi.good_edits = bdata.good_edits; dbvi.bad_edits = bdata.bad_edits; dbvec.push_back(dbvi); } cur->close(); } std::sort(dbvec.begin(), dbvec.end()); /*for(std::vector<std::pair<float,std::string> >::iterator it = dbvec.begin(); it != dbvec.end(); ++it) { if((*it).second != "_EDIT_TOTALS") cout << (*it).second << " " << (*it).first << "\n"; }*/ for(std::vector<dbvecinf>::iterator it = dbvec.begin(); it != dbvec.end(); ++it) { if(it->word != "_EDIT_TOTALS") cout << it->word << " " << it->score << " " << it->good_edits << " " << it->bad_edits << "\n"; } }
void berkeleydb_store<Object>::get_prev(const timestamp& time, const long lp_id, obj_ptr& ret_obj, timestamp& time_of_ret) { boost::lock_guard<boost::mutex> guard(get_mutex_); /* generate key */ std::vector<char> key; key_lpid_to_char(time, lp_id, key); Dbt db_key = Dbt(&key[0], key.size()); /* prepare data */ char* binary; Dbt data; data.set_data(binary); data.set_flags(DB_DBT_MALLOC); /* seek to key */ Dbc* cursorp; db->cursor(NULL, &cursorp, 0); int ret = cursorp->get(&db_key, &data, DB_SET_RANGE); /* seek back */ ret = cursorp->get(&db_key, &data, DB_PREV); /* get value */ std::string obj_binary = std::string((char*) data.get_data(), data.get_size()); std::stringstream ss; ss << obj_binary; boost::archive::binary_iarchive iar(ss); Object obj; iar >> obj; ret_obj = boost::make_shared<Object>(obj); /* get key */ long lp_id_; char_to_key_lpid((char*) db_key.get_data(), time_of_ret, lp_id_); if (cursorp != NULL) cursorp->close(); };
AvailGroupModel* AvailableGroups::loadData() { if (!model) { model = new AvailGroupModel(servers, groupDb,this); Dbt *key = 0, *data = 0; key=new Dbt; data=new Dbt; Dbc *cursor = 0; AvailableGroup *g = 0; if (groupDb->cursor(NULL, &cursor, 0)) qDebug() << "Error opening cursor"; int ret; quint32 count=0; while ((ret=cursor->get(key, data, DB_NEXT)) != DB_NOTFOUND) { g=new AvailableGroup((char*)data->get_data()); if (subscribedGroups->contains(g->getName())) g->setSubscribed(true); model->setupTopLevelItem(g); // add to model groupsList.insert(g->getName(), g); ++count; } qDebug() << "Available Groups: " << count; cursor->close(); Q_DELETE(key); Q_DELETE(data); } return model; }
known_peers::known_peers(boost::asio::io_service& io_service, const std::string& db_path, const author& signer) : db_(NULL, 0) , total_sent_(0) , total_received_(0) , next_rollover_(io_service) , max_credited_(boost::date_time::min_date_time) , signer_(signer) { db_.open(NULL, db_path.c_str(), NULL, DB_BTREE, DB_CREATE, 0); Dbc* cursor; db_.cursor(NULL, &cursor, 0); Dbt key, data; network_key id; key.set_flags(DB_DBT_USERMEM); key.set_data(&id); key.set_ulen(sizeof(network_key)); /* known_peer::packed peer_data; data.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); data.set_data(&peer_data); data.set_size(sizeof(peer_data)); */ while (cursor->get(&key, &data, DB_NEXT) == 0) { known_peer peer(reinterpret_cast<known_peer::packed*>(data.get_data())); peers_.insert(std::make_pair(id, peer)); total_sent_ += peer.total_sent(); total_received_ += peer.total_received(); } cursor->close(); rollover(boost::system::error_code()); }
/* This function is written specially for command line search. * It searches the region name db using an input string. * If the region name contains that string, the region name and its namespace * will be put into the string vector. * Returns 0 if everything is ok, non-zero otherwise. */ int findRegionNames(string dbHome, string dbName, string key_in, bool ik_flag, vector <regionRec> &outputList) { string keyStr = key_in; if (ik_flag) keyStr = toLowerCase(key_in); mydb regionDB(dbHome, dbName, DB_RDONLY); Dbc *cursorp; Dbt key, data; int ret; int foo = 0; try { regionDB.getDb().cursor(NULL, &cursorp, 0); while ((ret = cursorp->get(&key, &data, DB_NEXT)) == 0) { regionRec rData(data.get_data()); string rName = rData.getName(); if (ik_flag) rName = toLowerCase(rData.getName()); string rNS = rData.getNameSpace(); if (rName.find(keyStr) != string::npos) outputList.push_back(rData); } } catch(DbException &e) { regionDB.getDb().err(e.get_errno(), "Error in findRegionNames()"); foo = -1; } catch(exception &e) { regionDB.getDb().errx("Error in findRegionNames(): %s", e.what()); foo = -2; } cursorp->close(); return foo; }
/* This function collects relationship records that are not * "child" or "part-of" between r1 and r2 in relationship db. * Return -1 or -2 when exceptions are met; * Return 0 if everything is ok. */ int getRel_noChildPart(string dbHome, string rrDbName, long r1, long r2, vector <string> &relList) { mydb relationDB(dbHome, rrDbName, DB_RDONLY); string relStr; Dbc *cursorp; Dbt key, data; int ret; int foo = 0; try { relationDB.getDb().cursor(NULL, &cursorp, 0); while ((ret = cursorp->get(&key, &data, DB_NEXT)) == 0 ) { regionRelationRec rrData(data.get_data()); if (rrData.getRelationship() == "child" || rrData.getRelationship() == "part-of") continue; if (rrData.getRegion1() == r1 && rrData.getRegion2() == r2) { relStr = trRel_db2ui(rrData.getRelationship(), true); relList.push_back(relStr); } else if (rrData.getRegion1() == r2 && rrData.getRegion2() == r1) { relStr = trRel_db2ui(rrData.getRelationship(), false); relList.push_back(relStr); } } } catch(DbException &e) { relationDB.getDb().err(e.get_errno(), "Error in getRelation_all()"); foo = -1; } catch(exception &e) { relationDB.getDb().errx("Error in getRelation_all(): %s", e.what()); foo = -2; } cursorp->close(); return foo; }
/* This function collects all non-parent/child relationship records that involves rName_in. * It is written to show relationships on "search region" interface, so parent/child are ignored. * Return -1 or -2 when exceptions are met; * Return 0 if reading w/o error. */ int getRel_ui(string dbHome, string rrDbName, long rID_in, vector <long> &r2List, vector <string> &relList) { mydb relationDB(dbHome, rrDbName, DB_RDONLY); Dbc *cursorp; Dbt key, data; int ret; int foo = 0; try { relationDB.getDb().cursor(NULL, &cursorp, 0); while ((ret = cursorp->get(&key, &data, DB_NEXT)) == 0) { regionRelationRec rrData(data.get_data()); long r1 = rrData.getRegion1(); long r2 = rrData.getRegion2(); string tmpRel = rrData.getRelationship(); if (r1 == rID_in && tmpRel != "child") { r2List.push_back(r2); relList.push_back(trRel_db2ui(tmpRel, true)); } else if(r2 == rID_in && tmpRel != "child") { r2List.push_back(r1); relList.push_back(trRel_db2ui(tmpRel, false)); } } } catch(DbException &e) { relationDB.getDb().err(e.get_errno(), "Error in getRelation_ui()"); foo = -1; } catch(exception &e) { relationDB.getDb().errx("Error in getRelation_ui(): %s", e.what()); foo = -2; } cursorp->close(); return foo; }
/* This function collects parent and child region ID information and put in pID and cList. * Returns -1 or -2 if exception is met; * returns 0 if db file is read without error. */ int getParentChild(string dbHome, string rrDbName, long rID_in, long * pID, vector <long> &cList) { mydb regionRelationDB(dbHome, rrDbName, DB_RDONLY); Dbc *cursorp; Dbt key, data; int ret; int foo = 0; try { regionRelationDB.getDb().cursor(NULL, &cursorp, 0); while ((ret = cursorp->get(&key, &data, DB_NEXT)) == 0 ) { regionRelationRec rrData(data.get_data()); if (rrData.getRegion1() == rID_in && rrData.getRelationship() == "child") { if (*pID) printf("Multiple parent regions found for %ld: %ld and %d\n", rID_in, *pID, rrData.getRegion2()); else *pID = rrData.getRegion2(); } else if (rrData.getRegion2() == rID_in && rrData.getRelationship() == "child") { long cID = rrData.getRegion1(); cList.push_back(cID); } } } catch(DbException &e) { regionRelationDB.getDb().err(e.get_errno(), "Error in getParentChild()"); foo = -1; } catch(exception &e) { regionRelationDB.getDb().errx("Error in getParentChild(): %s", e.what()); foo = -2; } cursorp->close(); return foo; }
void MultiPartHeader::deleteAllParts(Db* pDB) { int ret = 0; Dbc *cursorp = 0; Dbt key; Dbt data; //qDebug() << "Deleting all parts for key " << multiPartKey; key.set_data(&multiPartKey); key.set_size(sizeof(quint64)); // Get a cursor pDB->cursor(NULL, &cursorp, DB_WRITECURSOR); while ((ret = cursorp->get(&key, &data, DB_SET)) == 0) cursorp->del(0); pDB->sync(0); if (cursorp != NULL) cursorp->close(); }
bool CDB::Rewrite(const string& strFile, const char* pszSkip) { while (!fShutdown) { { LOCK(bitdb.cs_db); if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0) { // Flush log data to the dat file bitdb.CloseDb(strFile); bitdb.CheckpointLSN(strFile); bitdb.mapFileUseCount.erase(strFile); bool fSuccess = true; printf("Rewriting %s...\n", strFile.c_str()); string strFileRes = strFile + ".rewrite"; { // surround usage of db with extra {} CDB db(strFile.c_str(), "r"); Db* pdbCopy = new Db(&bitdb.dbenv, 0); int ret = pdbCopy->open(NULL, // Txn pointer strFileRes.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { printf("Cannot create database file %s\n", strFileRes.c_str()); fSuccess = false; } Dbc* pcursor = db.GetCursor(); if (pcursor) while (fSuccess) { CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT); if (ret == DB_NOTFOUND) { pcursor->close(); break; } else if (ret != 0) { pcursor->close(); fSuccess = false; break; } if (pszSkip && strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0) continue; if (strncmp(&ssKey[0], "\x07version", 8) == 0) { // Update version: ssValue.clear(); ssValue << CLIENT_VERSION; } Dbt datKey(&ssKey[0], ssKey.size()); Dbt datValue(&ssValue[0], ssValue.size()); int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } if (fSuccess) { db.Close(); bitdb.CloseDb(strFile); if (pdbCopy->close(0)) fSuccess = false; delete pdbCopy; } } if (fSuccess) { Db dbA(&bitdb.dbenv, 0); if (dbA.remove(strFile.c_str(), NULL, 0)) fSuccess = false; Db dbB(&bitdb.dbenv, 0); if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0)) fSuccess = false; } if (!fSuccess) printf("Rewriting of %s FAILED!\n", strFileRes.c_str()); return fSuccess; } } MilliSleep(100); } return false; }
void AccessExample::run(bool removeExistingDatabase, const char *fileName) { // Remove the previous database. if (removeExistingDatabase) (void)remove(fileName); // Create the database object. // There is no environment for this simple example. Db db(0, 0); db.set_error_stream(&cerr); db.set_errpfx("AccessExample"); db.set_pagesize(1024); /* Page size: 1K. */ db.set_cachesize(0, 32 * 1024, 0); db.open(NULL, fileName, NULL, DB_BTREE, DB_CREATE, 0664); // // Insert records into the database, where the key is the user // input and the data is the user input in reverse order. // char buf[1024], rbuf[1024]; char *p, *t; int ret; u_int32_t len; for (;;) { cout << "input> "; cout.flush(); cin.getline(buf, sizeof(buf)); if (cin.eof()) break; if ((len = (u_int32_t)strlen(buf)) <= 0) continue; for (t = rbuf, p = buf + (len - 1); p >= buf;) *t++ = *p--; *t++ = '\0'; Dbt key(buf, len + 1); Dbt data(rbuf, len + 1); ret = db.put(0, &key, &data, DB_NOOVERWRITE); if (ret == DB_KEYEXIST) { cout << "Key " << buf << " already exists.\n"; } } cout << "\n"; // We put a try block around this section of code // to ensure that our database is properly closed // in the event of an error. // try { // Acquire a cursor for the table. Dbc *dbcp; db.cursor(NULL, &dbcp, 0); // Walk through the table, printing the key/data pairs. Dbt key; Dbt data; while (dbcp->get(&key, &data, DB_NEXT) == 0) { char *key_string = (char *)key.get_data(); char *data_string = (char *)data.get_data(); cout << key_string << " : " << data_string << "\n"; } dbcp->close(); } catch (DbException &dbe) { cerr << "AccessExample: " << dbe.what() << "\n"; } db.close(0); }