当前位置: 首页>>代码示例>>C++>>正文


C++ Dbc::get方法代码示例

本文整理汇总了C++中Dbc::get方法的典型用法代码示例。如果您正苦于以下问题:C++ Dbc::get方法的具体用法?C++ Dbc::get怎么用?C++ Dbc::get使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Dbc的用法示例。


在下文中一共展示了Dbc::get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: out

void
Freeze::MapHelperI::clear()
{
    DbTxn* txn = _connection->dbTxn();
    if(txn == 0)
    {
        closeAllIterators();
    }

    Dbt dbKey;
    dbKey.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL);

    Dbt dbValue;
    dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL);

    try
    {
        for(;;)
        {
            Dbc* dbc = 0;

            try
            {
                IteratorHelperI::TxPtr tx;
                if(txn == 0)
                {
#ifdef ICE_CPP11_COMPILER
                    tx.reset(new IteratorHelperI::Tx(*this));
#else
                    tx = new IteratorHelperI::Tx(*this);
#endif
                    txn = tx->getTxn();
                }

                _db->cursor(txn, &dbc, 0);
                while(dbc->get(&dbKey, &dbValue, DB_NEXT | DB_RMW) == 0)
                {
                    dbc->del(0);
                }

                Dbc* toClose = dbc;
                dbc = 0;
                toClose->close();
                break; // for (;;)
            }
            catch(const DbDeadlockException&)
            {
                if(dbc != 0)
                {
                    try
                    {
                        dbc->close();
                    }
                    catch(const DbDeadlockException&)
                    {
                        if(txn != 0)
                        {
                            throw;
                        }
                        else
                        {
                            //
                            // Ignored
                            //
                        }
                    }
                }

                if(_connection->deadlockWarning())
                {
                    Warning out(_connection->communicator()->getLogger());
                    out << "Deadlock in Freeze::MapHelperI::clear on Map \""
                        << _dbName << "\"; retrying ...";
                }

                if(txn != 0)
                {
                    throw;
                }
                //
                // Otherwise retry
                //
            }
            catch(...)
            {
                if(dbc != 0)
                {
                    try
                    {
                        dbc->close();
                    }
                    catch(const DbDeadlockException&)
                    {
                        if(txn != 0)
                        {
                            throw;
                        }
                        else
                        {
                            //
//.........这里部分代码省略.........
开发者ID:ming-hai,项目名称:freeze,代码行数:101,代码来源:MapI.cpp

示例2: initializeInDbt

int
Freeze::MapIndexI::untypedCount(const Key& k, const ConnectionIPtr& connection) const
{
    Dbt dbKey;
    initializeInDbt(k, dbKey);
#if (DB_VERSION_MAJOR <= 4)
    //
    // When we have a custom-comparison function, Berkeley DB returns
    // the key on-disk (when it finds one). We disable this behavior:
    // (ref Oracle SR 5925672.992)
    //
    dbKey.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL);
#else
    //
    // In DB 5.x we can not set DB_DBT_PARTIAL in the key Dbt,
    // when using DB_SET, we must resize the Dbt key param to hold enought
    // space or Dbc::get fails with DB_BUFFER_SMALL.
    //
    dbKey.set_flags(DB_DBT_USERMEM);
    dbKey.set_ulen(static_cast<u_int32_t>(k.size()));
#endif

    Dbt dbValue;
    dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL);

    int result = 0;

    DbTxn* txn = connection->dbTxn();

    try
    {
        for(;;)
        {
            Dbc* dbc = 0;

            try
            {
                //
                // Move to the first record
                //
                _db->cursor(txn, &dbc, 0);
                bool found = (dbc->get(&dbKey, &dbValue, DB_SET) == 0);

                if(found)
                {
                    db_recno_t count = 0;
                    dbc->count(&count, 0);
                    result = static_cast<int>(count);
                }

                Dbc* toClose = dbc;
                dbc = 0;
                toClose->close();
                break; // for (;;)
            }
            catch(const DbDeadlockException&)
            {
                if(dbc != 0)
                {
                    try
                    {
                        dbc->close();
                    }
                    catch(const DbDeadlockException&)
                    {
                        if(txn != 0)
                        {
                            throw;
                        }
                        else
                        {
                            //
                            // Ignored
                            //
                        }
                    }
                }

                if(connection->deadlockWarning())
                {
                    Warning out(connection->communicator()->getLogger());
                    out << "Deadlock in Freeze::MapIndexI::untypedCount while searching \""
                        << _dbName << "\"";
                }

                if(txn != 0)
                {
                    throw;
                }
                //
                // Otherwise retry
                //
            }
            catch(...)
            {
                if(dbc != 0)
                {
                    try
                    {
                        dbc->close();
//.........这里部分代码省略.........
开发者ID:ming-hai,项目名称:freeze,代码行数:101,代码来源:MapI.cpp

示例3: loadData

void QueueScheduler::loadData(Db* _schedDb, bool createStartup)
{
    Dbc *cursor = 0;
	Dbt key, data;
	uchar *keymem=new uchar[KEYMEM_SIZE];
	uchar *datamem=new uchar[DATAMEM_SIZE];

	key.set_flags(DB_DBT_USERMEM);
	key.set_data(keymem);
	key.set_ulen(KEYMEM_SIZE);

	data.set_flags(DB_DBT_USERMEM);
	data.set_ulen(DATAMEM_SIZE);
	data.set_data(datamem);

	int maxId = 0;

	int ret = 0;

	schedDb = _schedDb;

	schedDb->cursor(0, &cursor, DB_WRITECURSOR);

    QueueSchedule* queueSchedule = 0;

	while (ret == 0)
	{
		if ((ret = cursor->get(&key, &data, DB_NEXT)) == 0)
		{
			// qDebug() << "Just read schedule from Db, key = : " << key.get_data();
			queueSchedule = new QueueSchedule(schedDb, (uchar*)data.get_data(), this);
			queueSchedules.append(queueSchedule);
			currentSchedule = queueSchedule;
			if (queueSchedule->getIsActive())
				enabledSchedules.insert(queueSchedule->getPriority(), queueSchedule);
		}
		else if (ret == DB_BUFFER_SMALL)
		{
			ret = 0;
			qDebug("Insufficient memory");
			qDebug("Size required is: %d", data.get_size());
			uchar *p=datamem;
			datamem=new uchar[data.get_size()+1000];
			data.set_ulen(data.get_size()+1000);
			data.set_data(datamem);
            Q_DELETE_ARRAY(p);
		}
	}

	cursor->close();

	if (createStartup)
	{
		queueSchedule = new QueueSchedule(schedDb, tr("Un-metered"), this);
		queueSchedule->setIsActive(false);
		queueSchedule->setPriority(2);
		queueSchedule->addElement( 480 * 60, (1439 * 60) + 59, 128*1024, 0);
		queueSchedule->addElement(1920 * 60, (2879 * 60) + 59, 128*1024, 0);
		queueSchedule->addElement(3360 * 60, (4319 * 60) + 59, 128*1024, 0);
		queueSchedule->addElement(4800 * 60, (5759 * 60) + 59, 128*1024, 0);
		maxId = queueSchedule->addElement(6240 * 60, (7199 * 60) + 59, 128*1024, 0);
		queueSchedule->setMaxId(maxId);

		queueSchedules.append(queueSchedule);
		currentSchedule = queueSchedule;

		queueSchedule->dbSave();
	}

	managePeriods();

    Q_DELETE_ARRAY(keymem);
    Q_DELETE_ARRAY(datamem);
}
开发者ID:quban2,项目名称:quban,代码行数:74,代码来源:QueueScheduler.cpp

示例4: DatabaseException

/*static*/ void
Freeze::MapHelper::recreate(const Freeze::ConnectionPtr& connection,
                            const string& dbName,
                            const string& key,
                            const string& value,
                            const Freeze::KeyCompareBasePtr& keyCompare,
                            const std::vector<MapIndexBasePtr>& indices)
{
    Freeze::ConnectionIPtr connectionI = Freeze::ConnectionIPtr::dynamicCast(connection.get());
    if(connectionI == 0)
    {
        throw DatabaseException(__FILE__, __LINE__, "Invalid connection");
    }

    if(dbName == catalogName() || dbName == catalogIndexListName())
    {
        throw DatabaseException(__FILE__, __LINE__,
                                "You cannot destroy recreate the \"" + dbName + "\" database");
    }

    if(connectionI->trace() >= 1)
    {
        Trace out(connectionI->communicator()->getLogger(), "Freeze.Map");
        out << "Recreating \"" << dbName << "\"";
    }

    TransactionPtr tx = connectionI->currentTransaction();
    bool ownTx = (tx == 0);

    Dbt keyDbt;
    keyDbt.set_flags(DB_DBT_REALLOC);
    Dbt valueDbt;
    valueDbt.set_flags(DB_DBT_REALLOC);

    try
    {
        for(;;)
        {
            try
            {
                if(ownTx)
                {
                    tx = 0;
                    tx = connectionI->beginTransaction();
                }

                DbTxn* txn = connectionI->dbTxn();

                if(connectionI->trace() >= 2)
                {
                    Trace out(connectionI->communicator()->getLogger(), "Freeze.Map");
                    out << "Removing all existing indices for \"" << dbName << "\"";
                }
                CatalogIndexList catalogIndexList(connection, catalogIndexListName());
                CatalogIndexList::iterator p = catalogIndexList.find(dbName);
                if(p != catalogIndexList.end())
                {
                    const StringSeq& idxs = p->second;

                    for(size_t i = 0; i < idxs.size(); ++i)
                    {
                        try
                        {
                            connection->removeMapIndex(dbName, idxs[i]);
                        }
                        catch(const IndexNotFoundException&)
                        {
                            //
                            // Ignored
                            //
                        }
                    }
                    catalogIndexList.erase(p);
                }

                //
                // Rename existing database
                //
                string oldDbName = dbName + ".old-" + generateUUID();

                if(connectionI->trace() >= 2)
                {
                    Trace out(connectionI->communicator()->getLogger(), "Freeze.Map");
                    out << "Renaming \"" << dbName << "\" to \"" << oldDbName << "\"";
                }

                connectionI->dbEnv()->getEnv()->dbrename(txn, dbName.c_str(), 0, oldDbName.c_str(), 0);

                //
                // Fortunately, DB closes oldDb automatically when it goes out of scope
                //
                Db oldDb(connectionI->dbEnv()->getEnv(), 0);

                //
                // Berkeley DB expects file paths to be UTF8 encoded.
                //
                oldDb.open(txn, nativeToUTF8(oldDbName, getProcessStringConverter()).c_str(),
                           0, DB_BTREE, DB_THREAD, FREEZE_DB_MODE);

                IceInternal::UniquePtr<MapDb> newDb(new MapDb(connectionI, dbName, key, value, keyCompare, indices, true));
//.........这里部分代码省略.........
开发者ID:ming-hai,项目名称:freeze,代码行数:101,代码来源:MapI.cpp

示例5: k_histdbt

//
// XXX Figure out the appropriate way to pick out IDs.
//
int
TpcbExample::txn(Db *adb, Db *bdb, Db *tdb, Db *hdb,
		 int accounts, int branches, int tellers)
{
	Dbc *acurs = NULL;
	Dbc *bcurs = NULL;
	Dbc *tcurs = NULL;
	DbTxn *t = NULL;

	db_recno_t key;
	Defrec rec;
	Histrec hrec;
	int account, branch, teller, ret;

	Dbt d_dbt;
	Dbt d_histdbt;
	Dbt k_dbt;
	Dbt k_histdbt(&key, sizeof(key));

	// !!!
	// This is sample code -- we could move a lot of this into the driver
	// to make it faster.
	//
	account = random_id(ACCOUNT, accounts, branches, tellers);
	branch = random_id(BRANCH, accounts, branches, tellers);
	teller = random_id(TELLER, accounts, branches, tellers);

	k_dbt.set_size(sizeof(int));

	d_dbt.set_flags(DB_DBT_USERMEM);
	d_dbt.set_data(&rec);
	d_dbt.set_ulen(sizeof(rec));

	hrec.aid = account;
	hrec.bid = branch;
	hrec.tid = teller;
	hrec.amount = 10;
	// Request 0 bytes since we're just positioning.
	d_histdbt.set_flags(DB_DBT_PARTIAL);

	// START PER-TRANSACTION TIMING.
	//
	// Technically, TPCB requires a limit on response time, you only get
	// to count transactions that complete within 2 seconds.  That's not
	// an issue for this sample application -- regardless, here's where
	// the transaction begins.
	if (txn_begin(NULL, &t, 0) != 0)
		goto err;

	if (adb->cursor(t, &acurs, 0) != 0 ||
	    bdb->cursor(t, &bcurs, 0) != 0 ||
	    tdb->cursor(t, &tcurs, 0) != 0)
		goto err;

	// Account record
	k_dbt.set_data(&account);
	if (acurs->get(&k_dbt, &d_dbt, DB_SET) != 0)
		goto err;
	rec.balance += 10;
	if (acurs->put(&k_dbt, &d_dbt, DB_CURRENT) != 0)
		goto err;

	// Branch record
	k_dbt.set_data(&branch);
	if (bcurs->get(&k_dbt, &d_dbt, DB_SET) != 0)
		goto err;
	rec.balance += 10;
	if (bcurs->put(&k_dbt, &d_dbt, DB_CURRENT) != 0)
		goto err;

	// Teller record
	k_dbt.set_data(&teller);
	if (tcurs->get(&k_dbt, &d_dbt, DB_SET) != 0)
		goto err;
	rec.balance += 10;
	if (tcurs->put(&k_dbt, &d_dbt, DB_CURRENT) != 0)
		goto err;

	// History record
	d_histdbt.set_flags(0);
	d_histdbt.set_data(&hrec);
	d_histdbt.set_ulen(sizeof(hrec));
	if (hdb->put(t, &k_histdbt, &d_histdbt, DB_APPEND) != 0)
		goto err;

	if (acurs->close() != 0 || bcurs->close() != 0 || tcurs->close() != 0)
		goto err;

	ret = t->commit(0);
	t = NULL;
	if (ret != 0)
		goto err;

	// END PER-TRANSACTION TIMING.
	return (0);

err:
//.........这里部分代码省略.........
开发者ID:disenone,项目名称:wpython-2.7.11,代码行数:101,代码来源:TpcbExample.cpp

示例6: modifyPart

// Modify or create a part based on the following information
MultiPartHeader::Add_Code MultiPartHeader::modifyPart(Db* pdb, quint16 partNo, RawHeader *rh, quint16 hostId)
{
	//qDebug() << "Entering modifyPart";
    Add_Code retCode = New_Part;
	int ret = 0;
	bool createPart = false;
	Header* h = 0;
    char *phead = 0;
    Dbc *cursorp = 0;

	Dbt key;
	Dbt data;

	//qDebug() << "Creating part for key " << multiPartKey;

	key.set_data(&multiPartKey);
	key.set_size(sizeof(quint64));

	data.set_data(&partNo);
	data.set_size(sizeof(quint16));

	// Get a cursor
	pdb->cursor(NULL, &cursorp, DB_WRITECURSOR);
	//qDebug("1");

	// Position the cursor to the first record in the database whose
	// key matches the search key and whose data begins with the search
	// data.
	ret = cursorp->get(&key, &data, DB_GET_BOTH);
	if  (ret == 0)
	{
		//qDebug("2");
	    // update the data
		h = new Header((char*)data.get_data(), (char*)key.get_data());
		//qDebug("3");

		if (h->isHeldByServer(hostId))
		{
			retCode = Duplicate_Part;
		}
		else
			retCode = Updated_Part;

        // qDebug() << "Found an update for part " << partNo << ", existing part " << h->getPartNo() << ", existing msgid " << h->getMessageId() << ", new msgid " << rh->m_mid;

		// Always update the article number
		h->setServerPartNum(hostId, rh->m_num);

		//qDebug("4");
		phead=h->data();

		data.set_data(phead);
		data.set_size(h->getRecordSize());

		//qDebug("5");
		cursorp->put(&key, &data, DB_CURRENT);
		//qDebug("6");
        Q_DELETE_ARRAY(phead);
	}
	else if (ret == DB_NOTFOUND) // create the part
	{
		//qDebug("7");
		createPart = true;
	}
	else // encountered an error
	{
		qDebug() << "Unable to find part " << partNo << " for key " << multiPartKey << ", result = " << ret;
		retCode = Error_Part;
	}

	// Close the cursor
	if (cursorp != NULL)
	    cursorp->close();

	if (createPart == true)
	{
		//qDebug("8");
		quint32 partSize = rh->m_bytes.toULong();
		h = new Header(multiPartKey, partNo, partSize);

		//qDebug("9");

		h->setMessageId(rh->m_mid);
		h->setServerPartNum(hostId, rh->m_num);

		//save in the parts db
		phead=h->data();

		data.set_data(phead);
		data.set_size(h->getRecordSize());

		//qDebug("10");

		ret = pdb->put(0, &key, &data, 0);
		if (ret)
		{
		    qDebug() << "Unable to create part " << partNo << " for key " << multiPartKey << ", result = " << ret;
		    retCode = Error_Part;
		}
//.........这里部分代码省略.........
开发者ID:quban2,项目名称:quban,代码行数:101,代码来源:MultiPartHeader.cpp

示例7: run

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);
}
开发者ID:Pakrik,项目名称:libdb,代码行数:74,代码来源:AccessExample.cpp

示例8: run

void BtRecExample::run()
{
	db_recno_t recno;
	int ret;
	char buf[1024];

	// Acquire a cursor for the database.
	dbp->cursor(NULL, &dbcp, 0);

	//
	// Prompt the user for a record number, then retrieve and display
	// that record.
	//
	for (;;) {
		// Get a record number.
		cout << "recno #> ";
		cout.flush();
		if (fgets(buf, sizeof(buf), stdin) == NULL)
			break;
		recno = atoi(buf);

		//
		// Start with a fresh key each time,
		// the dbp->get() routine returns
		// the key and data pair, not just the key!
		//
		Dbt key(&recno, sizeof(recno));
		Dbt data;

		if ((ret = dbcp->get(&key, &data, DB_SET_RECNO)) != 0) {
			dbp->err(ret, "DBcursor->get");
			throw DbException(ret);
		}

		// Display the key and data.
		show("k/d\t", &key, &data);

		// Move the cursor a record forward.
		if ((ret = dbcp->get(&key, &data, DB_NEXT)) != 0) {
			dbp->err(ret, "DBcursor->get");
			throw DbException(ret);
		}

		// Display the key and data.
		show("next\t", &key, &data);

		//
		// Retrieve the record number for the following record into
		// local memory.
		//
		data.set_data(&recno);
		data.set_size(sizeof(recno));
		data.set_ulen(sizeof(recno));
		data.set_flags(data.get_flags() | DB_DBT_USERMEM);

		if ((ret = dbcp->get(&key, &data, DB_GET_RECNO)) != 0) {
			if (ret != DB_NOTFOUND && ret != DB_KEYEMPTY) {
				dbp->err(ret, "DBcursor->get");
				throw DbException(ret);
			}
		}
		else {
			cout << "retrieved recno: " << (u_long)recno << "\n";
		}
	}

	dbcp->close();
	dbcp = NULL;
}
开发者ID:disenone,项目名称:wpython-2.7.11,代码行数:69,代码来源:BtRecExample.cpp

示例9: run

void TestKeyRange::run()
{
	// Remove the previous database.
	(void)unlink(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("TestKeyRange");
	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];
	char rbuf[1024];
	char *t;
	char *p;
	int ret;
	int len;
	Dbt *firstkey = NULL;
	char firstbuf[1024];

	for (;;) {
		cout << "input>";
		cout.flush();

		cin.getline(buf, sizeof(buf));
		if (cin.eof())
			break;

		if ((len = 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);
		if (firstkey == NULL) {
			strcpy(firstbuf, buf);
			firstkey = new Dbt(firstbuf, 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);

		/*ADDED...*/
		DB_KEY_RANGE range;
		memset(&range, 0, sizeof(range));

		db.key_range(NULL, firstkey, &range, 0);
		printf("less: %f\n", range.less);
		printf("equal: %f\n", range.equal);
		printf("greater: %f\n", range.greater);
		/*end ADDED*/

		Dbt key;
		Dbt data;

		// Walk through the table, printing the key/data pairs.
		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 << "TestKeyRange: " << dbe.what() << "\n";
	}

	db.close(0);
}
开发者ID:crossbuild,项目名称:db,代码行数:92,代码来源:TestKeyRange.cpp

示例10: deactivateGuard

vector<Identity>::const_iterator
Freeze::EvictorIteratorI::nextBatch()
{
    DeactivateController::Guard 
        deactivateGuard(_store->evictor()->deactivateController());

    _batch.clear();

    if(!_more)
    {
        return _batch.end();
    }

    vector<EvictorElementPtr> evictorElements;
    evictorElements.reserve(_batchSize);
     
    Key firstKey = _key;

    CommunicatorPtr communicator = _store->communicator();
   
    try
    {
        for(;;)
        {
            _batch.clear();
            evictorElements.clear();
            
            Dbt dbKey;
            initializeOutDbt(_key, dbKey);

            Dbt dbValue;
            dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL);
           
            Dbc* dbc = 0;
            try
            {
                //
                // Move to the first record
                // 
                u_int32_t flags = DB_NEXT;

                if(_initialized)
                {
                    //
                    // _key represents the next element not yet returned
                    // if it has been deleted, we want the one after
                    //
                    flags = DB_SET_RANGE;

                    //
                    // Will be used as input as well
                    //
                    dbKey.set_size(static_cast<u_int32_t>(firstKey.size()));
                }
                
                _store->db()->cursor(0, &dbc, 0);

                bool done = false;
                do
                {
                    for(;;)
                    {
                        try
                        {
                            //
                            // It is critical to set key size to key capacity before the
                            // get, as a resize that increases the size inserts 0
                            //
                            _key.resize(_key.capacity());

                            _more = (dbc->get(&dbKey, &dbValue, flags) == 0);
                            if(_more)
                            {
                                _key.resize(dbKey.get_size());
                                _initialized = true;

                                flags = DB_NEXT;
                    
                                Ice::Identity ident;
                                ObjectStore::unmarshal(ident, _key, communicator);
                                if(_batch.size() < _batchSize)
                                {
                                    _batch.push_back(ident);
                                }
                                else
                                {
                                    //
                                    // Keep the last element in _key
                                    //
                                    done = true;
                                }
                            }
                            break;
                        }
                        catch(const DbDeadlockException&)
                        {
                            throw;
                        }
                        catch(const DbException& dx)
                        {
//.........这里部分代码省略.........
开发者ID:updowndown,项目名称:myffff,代码行数:101,代码来源:EvictorIteratorI.cpp

示例11: db

static void
transformDb(bool evictor,  const Ice::CommunicatorPtr& communicator,
            const FreezeScript::ValueFactoryPtr& valueFactory,
            DbEnv& dbEnv, DbEnv& dbEnvNew, const string& dbName,
            const Freeze::ConnectionPtr& connectionNew, vector<Db*>& dbs,
            const Slice::UnitPtr& oldUnit, const Slice::UnitPtr& newUnit,
            DbTxn* txnNew, bool purgeObjects, bool suppress, string descriptors)
{
    if(evictor)
    {
        //
        // The evictor database file contains multiple databases. We must first
        // determine the names of those databases, ignoring any whose names
        // begin with "$index:". Each database represents a separate facet, with
        // the facet name used as the database name. The database named "$default"
        // represents the main object.
        //
        vector<string> dbNames;
        {
            Db db(&dbEnv, 0);
            db.open(0, dbName.c_str(), 0, DB_UNKNOWN, DB_RDONLY, 0);
            Dbt dbKey, dbValue;
            dbKey.set_flags(DB_DBT_MALLOC);
            dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL);

            Dbc* dbc = 0;
            db.cursor(0, &dbc, 0);

            while(dbc->get(&dbKey, &dbValue, DB_NEXT) == 0)
            {
                string s(static_cast<char*>(dbKey.get_data()), dbKey.get_size());
                if(s.find("$index:") != 0)
                {
                    dbNames.push_back(s);
                }
                free(dbKey.get_data());
            }

            dbc->close();
            db.close(0);
        }

        //
        // Transform each database. We must delay closing the new databases
        // until after the transaction is committed or aborted.
        //
        for(vector<string>::iterator p = dbNames.begin(); p != dbNames.end(); ++p)
        {
            string name = p->c_str();

            Db db(&dbEnv, 0);
            db.open(0, dbName.c_str(), name.c_str(), DB_BTREE, DB_RDONLY, FREEZE_SCRIPT_DB_MODE);

            Db* dbNew = new Db(&dbEnvNew, 0);
            dbs.push_back(dbNew);
            dbNew->open(txnNew, dbName.c_str(), name.c_str(), DB_BTREE, DB_CREATE | DB_EXCL, FREEZE_SCRIPT_DB_MODE);

            //
            // Execute the transformation descriptors.
            //
            istringstream istr(descriptors);
            string facet = (name == "$default" ? string("") : name);
            FreezeScript::transformDatabase(communicator, valueFactory, oldUnit, newUnit, &db, dbNew, txnNew, 0,
                                            dbName, facet, purgeObjects, cerr, suppress, istr);

            db.close(0);
        }

        Freeze::Catalog catalogNew(connectionNew, Freeze::catalogName());
        Freeze::CatalogData catalogData = { true, "::Ice::Identity", "Object" };
        catalogNew.put(Freeze::Catalog::value_type(dbName, catalogData));
    }
    else
    {
        //
        // Transform a map database.
        //
        Db db(&dbEnv, 0);
        db.open(0, dbName.c_str(), 0, DB_BTREE, DB_RDONLY, FREEZE_SCRIPT_DB_MODE);

        Db* dbNew = new Db(&dbEnvNew, 0);
        dbs.push_back(dbNew);
        dbNew->open(txnNew, dbName.c_str(), 0, DB_BTREE, DB_CREATE | DB_EXCL, FREEZE_SCRIPT_DB_MODE);

        //
        // Execute the transformation descriptors.
        //
        istringstream istr(descriptors);
        FreezeScript::transformDatabase(communicator, valueFactory, oldUnit, newUnit, &db, dbNew, txnNew,
                                        connectionNew, dbName, "", purgeObjects, cerr, suppress, istr);

        db.close(0);
    }
}
开发者ID:zeroc-ice,项目名称:freeze,代码行数:94,代码来源:transformdb.cpp

示例12: scan

ScanResponse BDBBackend::scan (const string & bucket, const string & seed,
                               int32_t count)
{
    ScanResponse scan_response;

    Dbc * dbc;

    try
    {
        Dbt db_key;
        char key[BDB_BACKEND_MAX_KEY_SIZE + 1];
        db_key.set_data (key);
        db_key.set_ulen (BDB_BACKEND_MAX_KEY_SIZE + 1);
        db_key.set_flags (DB_DBT_USERMEM);
        Dbt db_value;
        char value[BDB_BACKEND_MAX_VALUE_SIZE + 1];
        db_value.set_data (value);
        db_value.set_ulen (BDB_BACKEND_MAX_VALUE_SIZE + 1);
        db_value.set_flags (DB_DBT_USERMEM);

        get_db (bucket)->cursor (NULL, &dbc, 0);

        // this get positions us at the last key we grabbed or the one
        // imediately following it
        // copy over the seed and it's size
        strncpy (key, seed.c_str (), seed.length () + 1);
        db_key.set_size (seed.length () + 1);
        if (dbc->get (&db_key, &db_value, DB_SET_RANGE) == 0)
        {
            string key_tmp ((const char *)db_key.get_data (),
                            db_key.get_size ());
            if (seed != key_tmp)
            {
                // we got the one after it, it must be gone now, so return
                // this one
                Element e;
                e.key = key_tmp;
                e.value = string ((const char *)db_value.get_data (),
                                  db_value.get_size ());
                scan_response.elements.push_back (e);
            } // we'll skip it, it's the one we had last time

            // now keep going until we run out of items or get our fill
            while ((dbc->get (&db_key, &db_value, DB_NEXT) == 0) &&
                    (scan_response.elements.size () < (unsigned int)count))
            {
                Element e;
                e.key = string ((const char *)db_key.get_data (),
                                db_key.get_size ());
                e.value = string ((const char *)db_value.get_data (),
                                  db_value.get_size ());
                scan_response.elements.push_back (e);
            }
        }
    }
    catch (DbDeadlockException & e)
    {
        T_INFO ("scan: exception=%s", e.what ());
        dbc->close ();
        throw e;
    }
    catch (DbException & e)
    {
        T_ERROR ("scan: exception=%s", e.what ());
        dbc->close ();
        throw e;
    }

    dbc->close ();

    scan_response.seed = scan_response.elements.size () > 0 ?
                         scan_response.elements.back ().key : "";

    return scan_response;
}
开发者ID:jakesays,项目名称:thrudb,代码行数:75,代码来源:BDBBackend.cpp

示例13: 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();
//.........这里部分代码省略.........
开发者ID:Mayalinux,项目名称:db,代码行数:101,代码来源:BulkExample.cpp

示例14: rundb

// Check that key/data for 0 - count-1 are already present,
// and write a key/data for count.  The key and data are
// both "0123...N" where N == count-1.
//
// For some reason on Windows, we need to open using the full pathname
// of the file when there is no environment, thus the 'has_env'
// variable.
//
void rundb(Db *db, int count, int has_env)
{
	const char *name;

	if (has_env)
		name = CONSTRUCT01_DBNAME;
	else
		name = CONSTRUCT01_DBFULLPATH;

	db->set_error_stream(&cerr);

	// We don't really care about the pagesize, but we do want
	// to make sure adjusting Db specific variables works before
	// opening the db.
	//
	CHK(db->set_pagesize(1024));
	CHK(db->open(NULL, name, NULL, DB_BTREE, count ? 0 : DB_CREATE, 0664));

	// The bit map of keys we've seen
	long bitmap = 0;

	// The bit map of keys we expect to see
	long expected = (1 << (count+1)) - 1;

	char outbuf[10];
	int i;
	for (i=0; i<count; i++) {
		outbuf[i] = '0' + i;
	}
	outbuf[i++] = '\0';
	Dbt key(outbuf, i);
	Dbt data(outbuf, i);

	DEBUGOUT("Put: " << outbuf);
	CHK(db->put(0, &key, &data, DB_NOOVERWRITE));

	// Acquire a cursor for the table.
	Dbc *dbcp;
	CHK(db->cursor(NULL, &dbcp, 0));

	// Walk through the table, checking
	Dbt readkey;
	Dbt readdata;
	while (dbcp->get(&readkey, &readdata, DB_NEXT) == 0) {
		char *key_string = (char *)readkey.get_data();
		char *data_string = (char *)readdata.get_data();
		DEBUGOUT("Got: " << key_string << ": " << data_string);
		int len = strlen(key_string);
		long bit = (1 << len);
		if (len > count) {
			ERR("reread length is bad");
		}
		else if (strcmp(data_string, key_string) != 0) {
			ERR("key/data don't match");
		}
		else if ((bitmap & bit) != 0) {
			ERR("key already seen");
		}
		else if ((expected & bit) == 0) {
			ERR("key was not expected");
		}
		else {
			bitmap |= bit;
			expected &= ~(bit);
			for (i=0; i<len; i++) {
				if (key_string[i] != ('0' + i)) {
					cout << " got " << key_string
					     << " (" << (int)key_string[i] << ")"
					     <<	", wanted " << i
					     << " (" << (int)('0' + i) << ")"
					     << " at position " << i << "\n";
					ERR("key is corrupt");
				}
			}
		}
	}
	if (expected != 0) {
		cout << " expected more keys, bitmap is: " << expected << "\n";
		ERR("missing keys in database");
	}
	CHK(dbcp->close());
	CHK(db->close(0));
}
开发者ID:disenone,项目名称:wpython-2.7.11,代码行数:91,代码来源:TestConstruct01.cpp

示例15: if

static int
run(const Ice::StringSeq& originalArgs, const Ice::CommunicatorPtr& communicator,
    const FreezeScript::CompactIdResolverIPtr& resolver)
{
    vector<string> cppArgs;
    bool debug;
    bool ice = true; // Needs to be true in order to create default definitions.
    bool underscore;
    string outputFile;
    string inputFile;
    vector<string> slice;
    bool evictor;
    string keyTypeName;
    string valueTypeName;
    string selectExpr;
    string dbEnvName, dbName;
    const string appName = originalArgs[0];
    IceUtilInternal::Options opts;
    opts.addOpt("h", "help");
    opts.addOpt("v", "version");
    opts.addOpt("D", "", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::Repeat);
    opts.addOpt("U", "", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::Repeat);
    opts.addOpt("I", "", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::Repeat);
    opts.addOpt("d", "debug");
    opts.addOpt("", "ice");
    opts.addOpt("", "underscore");
    opts.addOpt("o", "", IceUtilInternal::Options::NeedArg);
    opts.addOpt("f", "", IceUtilInternal::Options::NeedArg);
    opts.addOpt("", "load", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::Repeat);
    opts.addOpt("e");
    opts.addOpt("", "key", IceUtilInternal::Options::NeedArg);
    opts.addOpt("", "value", IceUtilInternal::Options::NeedArg);
    opts.addOpt("", "select", IceUtilInternal::Options::NeedArg);
    opts.addOpt("c", "catalog");

    vector<string> args;
    try
    {
        args = opts.parse(originalArgs);
    }
    catch(const IceUtilInternal::BadOptException& e)
    {
        cerr << appName << ": " << e.reason << endl;
        usage(appName);
        return EXIT_FAILURE;
    }

    //
    // Freeze creates a lock file by default to prevent multiple processes from opening
    // the same database environment simultaneously. In the case of a read-only program
    // such as dumpdb, however, we still want to be able to open the environment despite
    // the lock. This assumes of course that the other process has opened the environment
    // with DbPrivate=0. If DbPrivate=0 is also set for dumpdb, we disable the lock.
    //
    if(!args.empty())
    {
        //
        // If an argument is present, we assume it is the name of the database environment.
        //
        Ice::PropertiesPtr props = communicator->getProperties();
        string prefix = "Freeze.DbEnv." + args[0];
        if(props->getPropertyAsIntWithDefault(prefix + ".DbPrivate", 1) <= 0)
        {
            props->setProperty(prefix + ".LockFile", "0");
        }
    }

    if(opts.isSet("h"))
    {
        usage(appName);
        return EXIT_SUCCESS;
    }
    if(opts.isSet("version"))
    {
        cout << ICE_STRING_VERSION << endl;
        return EXIT_SUCCESS;
    }
    if(opts.isSet("c"))
    {
        if(args.empty())
        {
            cerr << appName << ": no database environment specified." << endl;
            usage(appName);
            return EXIT_FAILURE;
        }
        else if(args.size() > 2)
        {
            usage(appName);
            return EXIT_FAILURE;
        }
        try
        {
            FreezeScript::CatalogDataMap catalog = FreezeScript::readCatalog(communicator, args[0]);
            if(args.size() == 1)
            {
                if(catalog.empty())
                {
                    cout << "Catalog is empty." << endl;
                }
                else
//.........这里部分代码省略.........
开发者ID:pedia,项目名称:zeroc-ice,代码行数:101,代码来源:DumpDB.cpp


注:本文中的Dbc::get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。