本文整理汇总了C++中DbTxn::commit方法的典型用法代码示例。如果您正苦于以下问题:C++ DbTxn::commit方法的具体用法?C++ DbTxn::commit怎么用?C++ DbTxn::commit使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DbTxn
的用法示例。
在下文中一共展示了DbTxn::commit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: sendUsrInfo
/* Send user information to client.
* Message syntax check ignored !!!
* Returns 0 if everything is ok;
* retunrs -1 if user is not found and message is not sent out successfully;
* returns 1 if user is not found but message is sent out successfully;
* returns -2 if error occurs when browsing user table, and error message is not sent out successfully;
* returns 2 if error occurs when browsing user table, but error message is sent out successfully;
* returns 3 if user data is not sent out successfully. */
int srvSession::sendUsrInfo()
{
userRec myInfo;
DbTxn* txn = NULL;
dbs.env.getEnv()->txn_begin(NULL, &txn, 0);
int foo = getUser(dbs.userDB, txn, c_tokens[1], myInfo);
if (foo != 1) {
if (foo == 0) {
txn->commit(0);
statMsg = "no_data: User not found";
if (sendStatMsg())
return -1;
return 1;
}
else {
txn->abort();
statMsg = "no_data: DB error " + num2str(foo);
if (sendStatMsg())
return -2;
return 2;
}
}
txn->commit(0);
int data_size = myInfo.getSize();
char data_buf[data_size];
myInfo.serialize(data_buf);
// Send data to client
if (sendData(data_size, data_buf)) {
statMsg = "Error when sending user data to client: " + statMsg;
return 3;
}
return 0;
}
示例2: recvNewUsr
/* Receive updated user information data from client.
* Returns 0 if everything is ok;
* returns -1 if data size from client is invalid, and this error message is not sent out successfully;
* returns 1 if data size from client is invalid, but this error message is sent out successfully;
* returns -2 if user data is not received, and this error error message is not sent out successfully;
* returns 2 if user data is not received, but this error error message is sent out successfully;
* returns -3 if user account received already exists, and this error message is not sent out successfully;
* returns 3 if user account received already exists, but this error message is sent out successfully;
* returns -4 if error occurs when searching user table, and error message is not sent out successfully;
* returns 4 if error occurs when searching user table, but error message is sent out successfully;
* returns -5 if db error occurs when updating system time stamp, and error message is not sent out successfully;
* returns 5 if db error occurs when updating system time stamp, but error message is sent out successfully;
* returns -6 if server confirmation message is not sent out successfully. */
int srvSession::recvNewUsr()
{
int32 dat_size;
bool conv_stat = str2num(c_tokens[1], dat_size);
if (!conv_stat || dat_size <= 0) {
statMsg = "Invalid buffer size from client: " + c_tokens[1];
if (sendStatMsg())
return -1;
return 1;
}
char buffer[dat_size];
if (recvBuffer(g_session, dat_size, buffer)) {
statMsg = "Failed to receive new user data from client";
if (sendStatMsg())
return -2;
return 2;
}
DbTxn* txn = NULL;
dbs.env.getEnv()->txn_begin(NULL, &txn, 0);
int stat = addUser(dbs.userDB, dbs.sysDB, txn, buffer);
if (stat == 1) {
txn->commit(0);
statMsg = "Account already exists.";
if (sendStatMsg())
return -3;
return 3;
}
if (stat) {
txn->abort();
statMsg = "DB error when adding records into user table";
if (sendStatMsg())
return -4;
return 4;
}
if (setSysUpdate(dbs.sysDB, txn, statMsg)) {
txn->abort();
statMsg = "DB error when updating time stamp in system table: " + statMsg;
if (sendStatMsg())
return -5;
return 5;
}
txn->commit(0);
statMsg = "success";
if (sendStatMsg())
return -6;
dbs.sysDB.getDb().sync(0);
dbs.userDB.getDb().sync(0); // write data on disk now
return 0;
}
示例3: fprintf
/**
* Cursor must be closed before the transaction is aborted/commited.
* http://download.oracle.com/docs/cd/E17076_02/html/programmer_reference/transapp_cursor.html
*/
Bdb::ResponseCode Bdb::
update(const std::string& key, const std::string& value)
{
if (!inited_) {
fprintf(stderr, "insert called on uninitialized database");
return Error;
}
DbTxn* txn = NULL;
Dbc* cursor = NULL;
Dbt dbkey, dbdata;
dbkey.set_data(const_cast<char*>(key.c_str()));
dbkey.set_size(key.size());
dbdata.set_data(const_cast<char*>(value.c_str()));
dbdata.set_size(value.size());
Dbt currentData;
currentData.set_data(NULL);
currentData.set_ulen(0);
currentData.set_dlen(0);
currentData.set_doff(0);
currentData.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL);
int rc = 0;
for (uint32_t idx = 0; idx < numRetries_; idx++) {
env_->txn_begin(NULL, &txn, 0);
(*db_).cursor(txn, &cursor, DB_READ_COMMITTED);
// move the cursor to the record.
rc = cursor->get(&dbkey, ¤tData, DB_SET | DB_RMW);
if (rc != 0) {
cursor->close();
txn->abort();
if (rc == DB_NOTFOUND) {
return KeyNotFound;
} else if (rc != DB_LOCK_DEADLOCK) {
fprintf(stderr, "Db::get() returned: %s", db_strerror(rc));
return Error;
}
continue;
}
// update the record.
rc = cursor->put(NULL, &dbdata, DB_CURRENT);
cursor->close();
if (rc == 0) {
txn->commit(DB_TXN_SYNC);
return Success;
} else {
txn->abort();
if (rc != DB_LOCK_DEADLOCK) {
fprintf(stderr, "Db::put() returned: %s", db_strerror(rc));
return Error;
}
}
}
fprintf(stderr, "update failed %d times", numRetries_);
return Error;
}
示例4: initDb
/* Initialize the database. */
void BulkExample::initDb(int dups, int sflag, int pagesize) {
DbTxn *txnp;
int ret;
txnp = NULL;
ret = 0;
dbp = new Db(dbenv, 0);
dbp->set_error_stream(&cerr);
dbp->set_errpfx(progname);
try{
if ((ret = dbp->set_bt_compare(compare_int)) != 0)
throwException(dbenv, NULL, ret, "DB->set_bt_compare");
if ((ret = dbp->set_pagesize(pagesize)) != 0)
throwException(dbenv, NULL, ret, "DB->set_pagesize");
if (dups && (ret = dbp->set_flags(DB_DUP)) != 0)
throwException(dbenv, NULL, ret, "DB->set_flags");
if ((ret = dbenv->txn_begin(NULL, &txnp, 0)) != 0)
throwException(dbenv, NULL, ret, "DB_ENV->txn_begin");
if ((ret = dbp->open(txnp, DATABASE, "primary", DB_BTREE,
DB_CREATE, 0664)) != 0)
throwException(dbenv, txnp, ret, "DB->open");
if (sflag) {
sdbp = new Db(dbenv, 0);
if ((ret = sdbp->set_flags(DB_DUPSORT)) != 0)
throwException(dbenv, txnp,
ret, "DB->set_flags");
if ((ret = sdbp->open(txnp, DATABASE, "secondary",
DB_BTREE, DB_CREATE, 0664)) != 0)
throwException(dbenv, txnp, ret, "DB->open");
if ((ret = dbp->associate(
txnp, sdbp, get_first_str, 0)) != 0)
throwException(dbenv, txnp,
ret, "DB->associate");
}
ret = txnp->commit(0);
txnp = NULL;
if (ret != 0)
throwException(dbenv, NULL, ret, "DB_TXN->commit");
} catch(DbException &dbe) {
cerr << "initDb " << dbe.what() << endl;
if (txnp != NULL)
(void)txnp->abort();
throw dbe;
}
}
示例5: sendPatientMatches
/* Get a brief list of patients that matched cleint search criteria.
* Returns 0 if patient is found and data are sent out successfully,
* or no patient is found and message is sent out successfully;
* returns -1 if permission is denied and error message is not sent out successfully;
* returns 1 if permission is denied but error message is sent out successfully;
* returns -2 if search criterion is invalid and error message is not sent out successfully;
* returns 2 if search criterion is invalid but error message is sent out successfully;
* returns -3 if error occurs when searching patient and error message is not sent out successfully;
* returns 3 if error occurs when searching patient but error message is sent out successfully;
* returns -4 if no patient is found in db and message is not sent out successfully;
* returns -5 if patient is found but data are not sent out successfully. */
int srvSession::sendPatientMatches()
{
if (!permissions.size()) {
statMsg = "Permission denied";
if (sendStatMsg())
return -1;
return 1;
}
patientSearchTags ps_tags;
if (!parsePatientSearch(ps_tags)) {
statMsg = ps_tags.err_msg;
if (sendStatMsg())
return -2;
return 2;
}
DbTxn* txn = NULL;
dbs.env.getEnv()->txn_begin(NULL, &txn, 0);
vector<patientMatch> currentPatients;
int foo = searchPatients(dbs.scoreValueDB, txn, ps_tags, permissions, currentPatients);
if (foo < 0) {
txn->abort();
statMsg = "no_data: DB error ";
if (sendStatMsg())
return -3;
return 3;
}
txn->commit(0);
if (!currentPatients.size()) {
statMsg = "no_data: Patient not found";
if (sendStatMsg())
return -4;
return 0;
}
int32 dat_size = getSize(currentPatients);
char dat_buffer[dat_size];
serialize(currentPatients, dat_buffer);
if (sendData(dat_size, dat_buffer)) {
statMsg = "Error when sending patient search results to client: " + statMsg;
return -5;
}
return 0;
}
示例6: main
int main(int argc, char* argv[])
{
if (argc != 3) {
cout << "Usage: delRecord <db filename> <record id>" << endl;
exit(1);
}
string dbPath = argv[1];
string envHome;
string dbName;
if (!parseEnvPath(dbPath, envHome, dbName)) {
exit(1);
}
int32 id = atol(argv[2]);
if (id <= 0) {
cout << "Invalid ID: " << argv[2] << endl;
exit(1);
}
myEnv env(envHome);
if (!env.isOpen())
exit(1);
mydb currentDB(dbName, env);
if (!currentDB.isOpen()) {
env.close();
exit(1);
}
DbTxn* txn = NULL;
env.getEnv().txn_begin(NULL, &txn, 0);
Dbt key(&id, sizeof(id));
if (currentDB.getDb().del(txn, &key, 0) == 0) {
cout << "Record " << id << " is deleted" << endl;
txn->commit(0);
}
else {
cout << "Failed to delete record ID " << id << endl;
txn->abort();
}
currentDB.close();
env.close();
return 0;
}
示例7: recvScoreNames
/* Receive score name data from client side.
* Returns 0 if everything is ok;
* returns -1 if data size from client is invalid, and this error message is not sent out successfully;
* returns 1 if data size from client is invalid, but this error message is sent out successfully;
* returns -2 if data is not received, and this error error message is not sent out successfully;
* returns 2 if data is not received, but this error error message is sent out successfully;
* returns -3 if error occurs when searching db, and error message is not sent out successfully;
* returns 3 if error occurs when searching db, but error message is sent out successfully;
* returns -4 if db error occurs when updating system time stamp, and error message is not sent out successfully;
* returns 4 if db error occurs when updating system time stamp, but error message is sent out successfully;
* returns -5 if server confirmation message is not sent out successfully. */
int srvSession::recvScoreNames()
{
int32 dat_size;
bool conv_stat = str2num(c_tokens[1], dat_size);
if (!conv_stat || dat_size <= 0) {
statMsg = "Invalid score name data size from client: " + c_tokens[1];
if (sendStatMsg())
return -1;
return 1;
}
char buffer[dat_size];
if (recvBuffer(g_session, dat_size, buffer)) {
statMsg = "Failed to receive score names from client";
if (sendStatMsg())
return -2;
return 2;
}
vector<DBscorename> snList;
deserialize(dat_size, buffer, snList);
DbTxn* txn = NULL;
dbs.env.getEnv()->txn_begin(NULL, &txn, 0);
if (addScoreName(dbs.scoreNameDB, txn, snList)) {
txn->abort();
statMsg = "DB error when adding score name record into score name table";
if (sendStatMsg())
return -3;
return 3;
}
if (setSysUpdate(dbs.sysDB, txn, statMsg)) {
txn->abort();
statMsg = "DB error when updating time stamp in system table: " + statMsg;
if (sendStatMsg())
return -4;
return 4;
}
txn->commit(0);
dbs.scoreNameDB.getDb().sync(0);
dbs.sysDB.getDb().sync(0);
// Update score name maps on server side
vbforeach(DBscorename sn, snList) {
dbs.add_scorename(sn);
}
示例8: deleteOset
bool wb_db::deleteOset(pwr_tStatus *sts, wb_oset *o)
{
DbTxn *txn = 0;
m_env->txn_begin(m_txn, &txn, 0);
try {
//del_family(txn, o);
//unadopt(txn, wb_Position(o));
//del_ohead(txn, o);
//del_clist(txn, o);
//del_name(txn, o);
//del_body(txn, o);
txn->commit(0);
}
catch (DbException &e) {
txn->abort();
}
return true;
}
示例9: sendID
/* Send unique IDs to client side.
* Returns 0 if everything is ok;
* returns -1 if request from client is invalid and error message is not sent out successfully;
* returns 1 if request from client is invalid but error message is sent out successfully;
* returns -2 if error occurs when getting ID from db and error message is not sent out successfully;
* returns 2 if error occurs when getting ID from db but error message is sent out successfully;
* returns -3 if size of data is not sent out successfully;
* returns -4 if data are not sent out successfully. */
int srvSession::sendID()
{
int32 id_num;
bool conv_stat = str2num(c_tokens[1], id_num);
if (!conv_stat || id_num <= 0) {
statMsg = "no_data: Invalid number from client: " + c_tokens[1];
if (sendStatMsg())
return -1;
return 1;
}
DbTxn* txn = NULL;
dbs.env.getEnv()->txn_begin(NULL, &txn, 0);
int32 startID = getSysID(dbs.sysDB, txn, id_num);
if (startID <= 0) {
txn->abort();
statMsg = "no_data: DB error";
if (sendStatMsg())
return -2;
return 2;
}
txn->commit(0);
dbs.sysDB.getDb().sync(0); // write data on disk now
statMsg = "server_data_size: " + num2str(sizeof(startID));
if (sendStatMsg()) {
statMsg = "Error when sending ID to client: failed to send data size message";
return -3;
}
if (ntohs(1) == 1)
swap(&startID);
if (gnutls_record_send(g_session, &startID, sizeof(startID)) != sizeof(startID)) {
statMsg = "Error when sending ID to client: failed to send data";
return 4;
}
return 0;
}
示例10: db_key
void berkeleydb_store<Object>::put(const timestamp& time,
const long lp_id,
const Object& value) {
boost::lock_guard<boost::mutex> guard(put_mutex_);
/* generate key */
std::vector<char> key;
key_lpid_to_char(time, lp_id, key);
/* serialize object */
std::stringstream ss;
boost::archive::binary_oarchive ar(ss);
ar << value;
std::string binary = ss.str();
std::vector<char> put_event_binary(binary.begin(), binary.end());
Dbt db_key(&key[0], key.size());
Dbt data(&put_event_binary[0], put_event_binary.size());
DbTxn* txn = NULL;
env->txn_begin(NULL, &txn, 0);
int ret = db->put(txn, &db_key, &data, 0);
txn->commit(0);
};
示例11: log
//##############################################################################
//##############################################################################
BerkeleyDBCXXDb::BerkeleyDBCXXDb(const std::string &name,
boost::shared_ptr<BerkeleyDB> backend,
const boost::shared_ptr<db::ConfigIface> db_config, boost::shared_ptr<BerkeleyDBCXXEnv> env)
: name_(name), backend_(backend), env_(env), db_config_(db_config), log(BerkeleyDBCXXDbLogModule)
{
RANGE_LOG_FUNCTION();
inst_ = boost::make_shared<Db>(env_->getEnv(), 0);
int rval = 0;
DbTxn * txn;
try {
rval = env_->getEnv()->txn_begin(NULL, &txn, DB_TXN_SYNC | DB_TXN_WAIT | DB_TXN_SNAPSHOT);
}
catch(DbException &e) {
THROW_STACK(UnknownTransactionException(e.what()));
}
try {
inst_->open(txn, name.c_str(), name.c_str(), DB_HASH,
DB_CREATE | DB_MULTIVERSION | DB_THREAD, 0);
}
catch(DbException &e) {
txn->abort();
THROW_STACK(DatabaseEnvironmentException(e.what()));
}
catch(std::exception &e) {
txn->abort();
THROW_STACK(DatabaseEnvironmentException(e.what()));
}
switch(rval) {
case 0:
break;
case ENOMEM:
THROW_STACK(DatabaseEnvironmentException("The maximum number of concurrent transactions has been reached."));
}
txn->commit(0);
}
示例12: sync
//.........这里部分代码省略.........
long txnId = 0;
if(_txTrace >= 1)
{
txnId = (tx->id() & 0x7FFFFFFF) + 0x80000000L;
Trace out(_communicator->getLogger(), "Freeze.Evictor");
out << "started transaction " << hex << txnId << dec << " in saving thread";
}
try
{
for(size_t i = 0; i < txSize; i++)
{
StreamedObjectPtr obj = streamedObjectQueue[i];
Dbt key, value;
obj->key->getDbt(key);
if(obj->value)
{
obj->value->getDbt(value);
}
obj->store->save(key, value, obj->status, tx);
}
}
catch(...)
{
tx->abort();
if(_txTrace >= 1)
{
Trace out(_communicator->getLogger(), "Freeze.Evictor");
out << "rolled back transaction " << hex << txnId << dec;
}
throw;
}
tx->commit(0);
if(_txTrace >= 1)
{
Trace out(_communicator->getLogger(), "Freeze.Evictor");
out << "committed transaction " << hex << txnId << dec;
}
streamedObjectQueue.erase(streamedObjectQueue.begin(), streamedObjectQueue.begin() + txSize);
if(_trace >= 1)
{
Long now = IceUtil::Time::now(IceUtil::Time::Monotonic).toMilliSeconds();
Trace out(_communicator->getLogger(), "Freeze.Evictor");
out << "saved " << txSize << " objects in "
<< static_cast<Int>(now - saveStart) << " ms";
}
}
catch(const DbDeadlockException&)
{
if(_deadlockWarning)
{
Warning out(_communicator->getLogger());
out << "Deadlock in Freeze::BackgroundSaveEvictorI::run while writing into Db \"" + _filename
+ "\"; retrying ...";
}
tryAgain = true;
txSize = (txSize + 1)/2;
}
catch(const DbException& dx)
{
DatabaseException ex(__FILE__, __LINE__);
示例13: Recover
bool BerkeleyBatch::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename)
{
std::string filename;
BerkeleyEnvironment* env = GetWalletEnv(file_path, filename);
// Recovery procedure:
// move wallet file to walletfilename.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to fresh wallet file
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
newFilename = strprintf("%s.%d.bak", filename, now);
int result = env->dbenv->dbrename(nullptr, filename.c_str(), nullptr,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<BerkeleyEnvironment::KeyValPair> salvagedData;
bool fSuccess = env->Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(env->dbenv.get(), 0);
int ret = pdbCopy->open(nullptr, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("Cannot create database file %s\n", filename);
pdbCopy->close(0);
return false;
}
DbTxn* ptxn = env->TxnBegin();
for (BerkeleyEnvironment::KeyValPair& row : salvagedData)
{
if (recoverKVcallback)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
if (!(*recoverKVcallback)(callbackDataIn, ssKey, ssValue))
continue;
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
return fSuccess;
}
示例14: sendPatientScores
/* Get all scores of a certain patient.
* Returns 0 if everything is ok;
* returns -1 if permission is denied, and error message is not sent out successfully;
* returns 1 if permission is denied, but error message is sent out successfully;
* returns -2 if patient ID is invalid, and error message is not sent out successfully;
* returns 2 if patient ID is invalid, but error message is sent out successfully;
* returns -3 if error occurs when searching score value table, and error message is not sent out successfully;
* returns 3 if error occurs when searching score value table, but error message is sent out successfully;
* returns -4 if no score value record is found, and error message is not sent out successfully;
* returns 4 if no score value record is found, but error message is sent out successfully;
* returns -5 if data size message is not sent out successfully;
* returns -6 if score value data are not sent out successfully;
* returns -7 if no session is available, and the message is not sent out successfully;
* returns -8 if error occurs when searching session table, and error message is not sent out successfully;
* returns 8 if error occurs when searching session table, but error message is sent out successfully;
* returns -9 if session data are not sent out successfully. */
int srvSession::sendPatientScores()
{
if (!permissions.size()) {
statMsg = "Permission denied";
if (sendStatMsg())
return -1;
return 1;
}
// send error message to client if patient ID is invalid or score values not found
int32 pID;
bool conv_stat = str2num(c_tokens[1], pID);
if (!conv_stat || pID <= 0) {
statMsg = "no_data: Invalid patient ID " + c_tokens[1];
if (sendStatMsg())
return -2;
return 2;
}
// get score values
set<int32> sid_set;
DbTxn* txn = NULL;
dbs.env.getEnv()->txn_begin(NULL, &txn, 0);
Dbc* cursorp = NULL;
if (dbs.scoreValueDB.getDb().cursor(txn, &cursorp, 0)) {
txn->abort();
statMsg = "no_data: db error when searching score value table";
if (sendStatMsg())
return -3;
return 3;
}
// Iterate over score values table
Dbt key, data;
int ret;
int32 status = 0;
while ((ret = cursorp->get(&key, &data, DB_NEXT_NODUP)) == 0) {
DBscorevalue svData;
svData.deserializeHdr(data.get_data());
if (pID != svData.patient || svData.deleted)
continue;
string tmpPerm = getMaxPerm(svData, permissions);
if (tmpPerm.empty())
continue;
/* Add session IDs into session_list vector (session 0 is ignored here
* because this session doesn't exist in session table anyway) */
int32 sess_id = svData.sessionid;
if (sess_id)
sid_set.insert(sess_id);
// Add real score value records into DBscorevalue vector.
status = 1;
uint32 dat_size = data.get_size();
statMsg = "scorevalue: " + num2str(dat_size) + " " + tmpPerm;
if (sendStatMsg()) {
cursorp->close();
txn->abort();
return -4;
}
if (sendBuffer(g_session, dat_size, (char*) data.get_data())) {
statMsg = "Error when sending score value to client";
cursorp->close();
txn->abort();
return -4;
}
}
// Returns -1 if ret is non-zero and it doesn't reach the end of table
if (ret && ret != DB_NOTFOUND) {
cursorp->close();
txn->abort();
statMsg = "no_data: db error when searching score value table";
if (sendStatMsg())
return -3;
return 3;
}
cursorp->close();
if (status == 0) {
txn->commit(0);
statMsg = "no_scorevalue";
if (sendStatMsg())
//.........这里部分代码省略.........
示例15: bulkRead
/* Loop get batches of records. */
void BulkExample::bulkRead(
int num, int dups, int iter, int *countp, int verbose)
{
Dbc *dbcp;
Dbt data, dp, key, kp;
DbTxn *txnp;
DbMultipleDataIterator *ptrd;
DbMultipleKeyDataIterator *ptrkd;
u_int32_t flags;
int count, i, j, ret;
count = klen = ret = 0;
dbcp = NULL;
txnp = NULL;
/* Initialize key Dbt and data Dbt, malloc bulk buffer. */
memset(&key, 0, sizeof(key));
memset(&data, 0, sizeof(data));
key.set_size(sizeof(j));
if (dlen != DATALEN * 16 * 1024) {
dlen = DATALEN * 16 * 1024;
dbuf = realloc(dbuf, dlen);
}
memset(dbuf, 0, dlen);
data.set_flags(DB_DBT_USERMEM);
data.set_data(dbuf);
data.set_ulen(dlen);
data.set_size(dlen);
flags = DB_SET;
flags |= (dups) ? DB_MULTIPLE: DB_MULTIPLE_KEY;
try {
for (i = 0; i < iter; i++) {
if ((ret =
dbenv->txn_begin(NULL, &txnp, 0)) != 0)
throwException(dbenv, NULL,
ret, "DB_ENV->txn_begin");
if ((ret = dbp->cursor(txnp, &dbcp, 0)) != 0)
throwException(dbenv, txnp,
ret, "DB->cursor");
/*
* Bulk retrieve by a random key which is a random
* non-negative integer smaller than "num".
* If there are duplicates in the database, retrieve
* with DB_MULTIPLE and use the DbMultipleDataIterator
* to iterate the data of the random key in the data
* Dbt. Otherwise retrieve with DB_MULTIPLE_KEY and use
* the DbMultipleKeyDataIterator to iterate the
* key/data pairs of the specific set of keys which
* includes all integers >= the random key and < "num".
*/
j = rand() % num;
key.set_data(&j);
if ((ret = dbcp->get(&key, &data, flags)) != 0)
throwException(dbenv, NULL, ret, "DBC->get");
if (dups) {
ptrd = new DbMultipleDataIterator(data);
while (ptrd->next(dp) == true) {
count++;
if (verbose)
printf(
"Retrieve key: %d, \tdata: (id %d, str %s)\n", j, ((struct data *)(
dp.get_data()))->id,
(char *)((struct data *)(
dp.get_data()))->str);
}
} else {
ptrkd = new DbMultipleKeyDataIterator(data);
while (ptrkd->next(kp, dp) == true) {
count++;
if (verbose)
printf(
"Retrieve key: %d, \tdata: (id %d, str %s)\n", *((int *)kp.get_data()),
((struct data *)(
dp.get_data()))->id,
(char *)((struct data *)(
dp.get_data()))->str);
}
}
ret = dbcp->close();
dbcp = NULL;
if (ret != 0)
throwException(dbenv, txnp, ret, "DBC->close");
ret = txnp->commit(0);
txnp = NULL;
if (ret != 0)
throwException(dbenv, NULL,
ret, "DB_TXN->commit");
}
*countp = count;
} catch (DbException &dbe) {
cerr << "bulkRead " << dbe.what() << endl;
if (dbcp != NULL)
(void)dbcp->close();
//.........这里部分代码省略.........