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


C++ prepare函数代码示例

本文整理汇总了C++中prepare函数的典型用法代码示例。如果您正苦于以下问题:C++ prepare函数的具体用法?C++ prepare怎么用?C++ prepare使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: prepare

void Database::execute(const String &request)
{
	Statement statement = prepare(request);
	statement.step();
	statement.finalize();
}
开发者ID:orinocoz,项目名称:Teapotnet,代码行数:6,代码来源:database.cpp

示例2: uassertStatusOK

    long long DeleteExecutor::execute(Database* db) {
        uassertStatusOK(prepare());
        uassert(17417,
                mongoutils::str::stream() <<
                "DeleteExecutor::prepare() failed to parse query " << _request->getQuery(),
                _isQueryParsed);

        const NamespaceString& ns(_request->getNamespaceString());
        if (!_request->isGod()) {
            if (ns.isSystem()) {
                uassert(12050,
                        "cannot delete from system namespace",
                        legalClientSystemNS(ns.ns(), true));
            }
            if (ns.ns().find('$') != string::npos) {
                log() << "cannot delete from collection with reserved $ in name: " << ns << endl;
                uasserted(10100, "cannot delete from collection with reserved $ in name");
            }
        }

        Collection* collection = db->getCollection(_request->getOpCtx(), ns.ns());
        if (NULL == collection) {
            return 0;
        }

        uassert(10101,
                str::stream() << "cannot remove from a capped collection: " << ns.ns(),
                !collection->isCapped());

        uassert(ErrorCodes::NotMaster,
                str::stream() << "Not primary while removing from " << ns.ns(),
                !_request->shouldCallLogOp() ||
                repl::getGlobalReplicationCoordinator()->canAcceptWritesForDatabase(ns.db()));

        PlanExecutor* rawExec;
        if (_canonicalQuery.get()) {
            // This is the non-idhack branch.
            uassertStatusOK(getExecutorDelete(_request->getOpCtx(), collection,
                                              _canonicalQuery.release(), _request->isMulti(),
                                              _request->shouldCallLogOp(), &rawExec));
        }
        else {
            // This is the idhack branch.
            uassertStatusOK(getExecutorDelete(_request->getOpCtx(), collection, ns.ns(),
                                              _request->getQuery(), _request->isMulti(),
                                              _request->shouldCallLogOp(), &rawExec));
        }
        scoped_ptr<PlanExecutor> exec(rawExec);

        // Concurrently mutating state (by us) so we need to register 'exec'.
        const ScopedExecutorRegistration safety(exec.get());

        uassertStatusOK(exec->executePlan());

        // Extract the number of documents deleted from the DeleteStage stats.
        invariant(exec->getRootStage()->stageType() == STAGE_DELETE);
        DeleteStage* deleteStage = static_cast<DeleteStage*>(exec->getRootStage());
        const DeleteStats* deleteStats =
            static_cast<const DeleteStats*>(deleteStage->getSpecificStats());
        return deleteStats->docsDeleted;
    }
开发者ID:Mickael-van-der-Beek,项目名称:mongo,代码行数:61,代码来源:delete_executor.cpp

示例3: prepare

int dtObstacleAvoidanceQuery::sampleVelocityAdaptive(const float* pos, const float rad, const float vmax,
													 const float* vel, const float* dvel, float* nvel,
													 const dtObstacleAvoidanceParams* params,
													 dtObstacleAvoidanceDebugData* debug)
{
	prepare(pos, dvel);
	
	memcpy(&m_params, params, sizeof(dtObstacleAvoidanceParams));
	m_invHorizTime = 1.0f / m_params.horizTime;
	m_vmax = vmax;
	m_invVmax = 1.0f / vmax;
	
	dtVset(nvel, 0,0,0);
	
	if (debug)
		debug->reset();

	// Build sampling pattern aligned to desired velocity.
	float pat[(DT_MAX_PATTERN_DIVS*DT_MAX_PATTERN_RINGS+1)*2];
	int npat = 0;

	const int ndivs = (int)m_params.adaptiveDivs;
	const int nrings= (int)m_params.adaptiveRings;
	const int depth = (int)m_params.adaptiveDepth;
	
	const int nd = dtClamp(ndivs, 1, DT_MAX_PATTERN_DIVS);
	const int nr = dtClamp(nrings, 1, DT_MAX_PATTERN_RINGS);
	const float da = (1.0f/nd) * DT_PI*2;
	const float dang = atan2f(dvel[2], dvel[0]);
	
	// Always add sample at zero
	pat[npat*2+0] = 0;
	pat[npat*2+1] = 0;
	npat++;
	
	for (int j = 0; j < nr; ++j)
	{
		const float rad = (float)(nr-j)/(float)nr;
		float a = dang + (j&1)*0.5f*da;
		for (int i = 0; i < nd; ++i)
		{
			pat[npat*2+0] = cosf(a)*rad;
			pat[npat*2+1] = sinf(a)*rad;
			npat++;
			a += da;
		}
	}

	// Start sampling.
	float cr = vmax * (1.0f - m_params.velBias);
	float res[3];
	dtVset(res, dvel[0] * m_params.velBias, 0, dvel[2] * m_params.velBias);
	int ns = 0;

	for (int k = 0; k < depth; ++k)
	{
		float minPenalty = FLT_MAX;
		float bvel[3];
		dtVset(bvel, 0,0,0);
		
		for (int i = 0; i < npat; ++i)
		{
			float vcand[3];
			vcand[0] = res[0] + pat[i*2+0]*cr;
			vcand[1] = 0;
			vcand[2] = res[2] + pat[i*2+1]*cr;
			
			if (dtSqr(vcand[0])+dtSqr(vcand[2]) > dtSqr(vmax+0.001f)) continue;
			
			const float penalty = processSample(vcand,cr/10, pos,rad,vel,dvel, debug);
			ns++;
			if (penalty < minPenalty)
			{
				minPenalty = penalty;
				dtVcopy(bvel, vcand);
			}
		}

		dtVcopy(res, bvel);

		cr *= 0.5f;
	}	
	
	dtVcopy(nvel, res);
	
	return ns;
}
开发者ID:120pulsations,项目名称:SDK,代码行数:87,代码来源:DetourObstacleAvoidance.cpp

示例4: mState

Regex::Regex( const JHSTD::string &regex ) : mState( Regex::STATE_INIT )
{
	prepare( regex );
}
开发者ID:benpayne,项目名称:jhcommon,代码行数:4,代码来源:Regex.cpp

示例5: main


//.........这里部分代码省略.........
			}
		sscanf(argv[argno++],"%f",&duration);
		if (sscanf(argv[argno],"%d",(int *)&child) != 1)
			{
			child = 0;
			}
		if (child == 0)
			{
			int i,len;
#if NEVER
			char *p;
#endif
			/* skip two: the prog name, and the duration.  And then we need
			 * an extra one for the new prog name: 1+1-1 is 1.
			 */
			len = argc - 1;
			arg_vec = malloc(sizeof(char *)*len);
			if (arg_vec == NULL)
				{
				fprintf(stderr,"malloc failed\n");
				exit(1);
				}
			for (i=0; i<len-1; i++)
				{
				arg_vec[i] = argv[i+argno];
				}
			arg_vec[len-1] = NULL;
			if (verbose)
				{
				fprintf(stderr,"Attempting to monitor new prog %s\n",arg_vec[0]);
				}
#if NEVER
			for (p=&(arg_vec[0]); p != NULL; p++)
				{
				fprintf(stderr,"arg_vec[%d] is %s\n", p - &(arg_vec[0]), p);
				}
#endif
			for (i=0; i < len; i++)
				{
				if (arg_vec[i] == NULL)
					{
					if (verbose)
						{
						fprintf(stderr,"arg_vec[%d] is %s\n", i, "NULL");
						}
					}
				else
					{
					if (verbose)
						{
						fprintf(stderr,"arg_vec[%d] is %s\n", i, arg_vec[i]);
						}
					}
				}
			}
		else
			{
			if (verbose)
				{
				fprintf(stderr,"Attempting to monitor preexisting pid %d\n",
					(int)child);
				}
			}
		}
	else
		{
		usage(argv[0]);
		}
	/* for use by caught_signal */
	global.child = child;
	global.argv0 = argv[0];
	signal(SIGTERM,caught_signal);
	signal(SIGINT,caught_signal);
	if (arg_vec == NULL)
		{
		monitor(child,duration,0,verbose);
		}
	else
		{
		child = fork();
		if (child == 0)
			{
			prepare();
			if (verbose)
				{
				fprintf(stderr,"Exec'ing %s in 2 seconds\n",arg_vec[0]);
				}
			/* ugly race window */
			sleep(2);
			execvp(arg_vec[0], &(arg_vec[0]));
			perror("execl failed");
			exit(1);
			}
		else
			{
			monitor(child,duration,1,verbose);
			}
		}
   return 0;
   }
开发者ID:woytekm,项目名称:IRIS,代码行数:101,代码来源:common.c

示例6: prepare

	statement session::operator<<(char const *s)
	{
		return prepare(s);
	}
开发者ID:guangzhuwu,项目名称:p2streaming,代码行数:4,代码来源:frontend.cpp

示例7: prepare

void Transmitter::answer()
{
	prepare();
	sendAnswerPacket();
}
开发者ID:nightfly19,项目名称:renyang-learn,代码行数:5,代码来源:Transmitter.cpp

示例8: myTosplit

StringTokenizer::StringTokenizer(std::string tosplit, std::string token, bool splitAtAllChars)
        : myTosplit(tosplit), myPos(0) {
    prepare(tosplit, token, splitAtAllChars);
}
开发者ID:NeziheSozen,项目名称:sumo,代码行数:4,代码来源:StringTokenizer.cpp

示例9: main


//.........这里部分代码省略.........
	}
	if (count > 1) {
		args[count-1] = (char*)malloc(sizeof(char)*4);
		strcpy(args[count-1],"-ac"); count++;
		args[count-1] = NULL;
	} else {
		args[count] = (char*)malloc(sizeof(char*)*4);
		strcpy(args[count],"-ac"); count++;
		args[count] = NULL;
	}

	//=========================================
	// setup signal handler
	//-----------------------------------------
	signal (SIGHUP  , trapper);
	signal (SIGINT  , trapper);
	signal (SIGTERM , trapper);
	signal (SIGPIPE , trapper);
	signal (SIGCHLD , child  );

	if ((fd = open(PATH_DEV_NULL, O_RDWR, 0)) != -1) {
		dup2  ( fd, STDERR_FILENO );
		close ( fd );
	}

	cpid = fork();
	switch (cpid) {
	case -1:
		// ...
		// can not fork
		// ---
		perror("fork"); exit(1);
	break;
	case 0:
		// ...
		// child process...
		// ---
		if (logfile != NULL) {
			data = freopen (logfile,"w",stderr );
			setvbuf ( data,(char*)NULL,_IONBF,0 );
		}
		execv (XFree86,args);
	break;
	default:
		// ...
		// parent process
		// ---
		break;
	}
	while ( timeout > 0  ) {
	sleep ( timeout -= 2 );
	if ( waitpid ( cpid, &status, WNOHANG | WUNTRACED) == cpid ) {
		break;
	} else {
		dpy = XOpenDisplay (displayname);
		if (dpy != NULL) {
			break;
		}
	}
	}
	if (dpy == NULL) {
		exit(1);
	}
	prepare ();
	//=====================================
	// start idle timer logtimer is set
	//-------------------------------------
	if (logtimer) {
		char pidToKill [20] = "";
		sprintf (pidToKill,"%d",looppid);
		if (blank) {
			sprintf (pidToKill,"%d",cpid);
		}
		timerpid = fork();
		switch (timerpid) {
		case -1:
			perror("fork"); exit(1);
		break;
		case 0:
			execl (XIDLE,
				"xapi","-x","-p",pidToKill,"-display",displayname,NULL
			);
		break;
		default:
		waitpid (
			timerpid, NULL, WNOHANG | WUNTRACED
		);
		}
	}
	if (! blank) {
	if (! kill (looppid,0)) {
		printf ("%d\n",cpid);
	} else {
		printf ("%d\n",looppid);
	}
	} else {
		printf ("%d\n",cpid);
	}
	exit (0);
}
开发者ID:BackupTheBerlios,项目名称:sax-svn,代码行数:101,代码来源:xw.c

示例10: prepare

QString DialogFilter::getWhere()
{
    QString result = prepare(fieldsCollection.at(cbField->itemData(cbField->currentIndex()).toInt()),cbExpression->itemData(cbExpression->currentIndex()).toString(),edExpression->text());
    if (result == "") result =  "1 = 2";
    return result;
}
开发者ID:Voral,项目名称:qtDbf,代码行数:6,代码来源:dialogfilter.cpp

示例11: Q_ASSERT

/**
 * Copies selected files into sandbox. Existing files in sandbox are not overwriten.
 *
 * @c QDir::NoDotAndDotDot is always added into @a filters.
 */
bool Sandbox::addWorldFiles(const QString &directory, QDir::Filters filters,
    const QStringList &filterNames, bool recurse){
  Q_ASSERT(!isActive());
  Q_ASSERT(!directory.isEmpty());

  if (!prepare()){
    return false;
  }

  const QString sandboxedDirectory = m_workingSandboxDir.filePath(
      QDir::root().relativeFilePath(
        QFileInfo(directory).absoluteFilePath()));

  if (!QFileInfo(directory).exists()){
    // Accept missing world directory - allow to create directories inside sandbox
    qDebug("%s: Directory does not exist - an empty one will be created instead of copied: '%s'",
        Q_FUNC_INFO, qPrintable(directory));
  } else if (!QFileInfo(directory).isDir()){
    qWarning("%s: Is not a directory: '%s'", Q_FUNC_INFO, qPrintable(directory));
    return false;
  }

  if (!QFileInfo(sandboxedDirectory).exists()){
    if (!QDir().mkpath(sandboxedDirectory)){
      qWarning("%s: Failed to create sandbox directory '%s'", Q_FUNC_INFO,
          qPrintable(sandboxedDirectory));
      return false;
    }
  } else if (!QFileInfo(sandboxedDirectory).isDir()){
    qWarning("%s: Failed to create sandbox directory '%s': Is not a directory", Q_FUNC_INFO,
        qPrintable(sandboxedDirectory));
    return false;
  }

  if (filters == QDir::NoFilter){
    filters = QDir::AllEntries;
  }

  filters |= QDir::NoDotAndDotDot;

  foreach (const QFileInfo &worldEntryInfo, QDir(directory).entryInfoList(filterNames, filters)){

    const QFileInfo sandboxEntryInfo(QDir(sandboxedDirectory).filePath(worldEntryInfo.fileName()));

    if (worldEntryInfo.isDir()){
      if (!sandboxEntryInfo.exists()){
        if (!QDir(sandboxedDirectory).mkdir(worldEntryInfo.fileName())){
          qWarning("%s: Failed to create overlay directory '%s/%s'", Q_FUNC_INFO,
              qPrintable(sandboxedDirectory), qPrintable(worldEntryInfo.fileName()));
          return false;
        }
      } else if (!sandboxEntryInfo.isDir()){
          qWarning("%s: Failed to create sandboxed copy '%s': Is not a directory", Q_FUNC_INFO,
              qPrintable(sandboxEntryInfo.filePath()));
          return false;
      }

      if (recurse){
        if (!addWorldFiles(worldEntryInfo.absoluteFilePath(), filters, filterNames, true)){
          return false;
        }
      }
    } else{
      if (!sandboxEntryInfo.exists()){
        if (!QFile(worldEntryInfo.filePath()).copy(sandboxEntryInfo.filePath())){
          qWarning("%s: Failed to copy file into sandbox '%s'", Q_FUNC_INFO,
              qPrintable(worldEntryInfo.filePath()));
          return false;
        }
      } else if (sandboxEntryInfo.isDir()){
          qWarning("%s: Failed to create sandboxed copy '%s': Is a directory", Q_FUNC_INFO,
              qPrintable(sandboxEntryInfo.filePath()));
          return false;
      }
    }
  }

  return true;
}
开发者ID:chriadam,项目名称:ssu,代码行数:84,代码来源:sandbox.cpp

示例12: prepare

int dtObstacleAvoidanceQuery::sampleVelocityAdaptive(const float* pos, const float rad, const float vmax,
													 const float* vel, const float* dvel, float* nvel,
													 const dtObstacleAvoidanceParams* params,
													 dtObstacleAvoidanceDebugData* debug)
{
	prepare(pos, dvel);
	
	memcpy(&m_params, params, sizeof(dtObstacleAvoidanceParams));
	m_invHorizTime = 1.0f / m_params.horizTime;
	m_vmax = vmax;
	m_invVmax = vmax > 0 ? 1.0f / vmax : FLT_MAX;
	
	dtVset(nvel, 0,0,0);
	
	if (debug)
		debug->reset();

	// Build sampling pattern aligned to desired velocity.
	float pat[(DT_MAX_PATTERN_DIVS*DT_MAX_PATTERN_RINGS+1)*2];
	int npat = 0;

	const int ndivs = (int)m_params.adaptiveDivs;
	const int nrings= (int)m_params.adaptiveRings;
	const int depth = (int)m_params.adaptiveDepth;
	
	const int nd = dtClamp(ndivs, 1, DT_MAX_PATTERN_DIVS);
	const int nr = dtClamp(nrings, 1, DT_MAX_PATTERN_RINGS);
	const int nd2 = nd / 2;
	const float da = (1.0f/nd) * DT_PI*2;
	const float ca = cosf(da);
	const float sa = sinf(da);

	// desired direction
	float ddir[6];
	dtVcopy(ddir, dvel);
	dtNormalize2D(ddir);
	dtRorate2D (ddir+3, ddir, da*0.5f); // rotated by da/2

	// Always add sample at zero
	pat[npat*2+0] = 0;
	pat[npat*2+1] = 0;
	npat++;
	
	for (int j = 0; j < nr; ++j)
	{
		const float r = (float)(nr-j)/(float)nr;
		pat[npat*2+0] = ddir[(j%1)*3] * r;
		pat[npat*2+1] = ddir[(j%1)*3+2] * r;
		float* last1 = pat + npat*2;
		float* last2 = last1;
		npat++;

		for (int i = 1; i < nd-1; i+=2)
		{
			// get next point on the "right" (rotate CW)
			pat[npat*2+0] = last1[0]*ca + last1[1]*sa;
			pat[npat*2+1] = -last1[0]*sa + last1[1]*ca;
			// get next point on the "left" (rotate CCW)
			pat[npat*2+2] = last2[0]*ca - last2[1]*sa;
			pat[npat*2+3] = last2[0]*sa + last2[1]*ca;

			last1 = pat + npat*2;
			last2 = last1 + 2;
			npat += 2;
		}

		if ((nd&1) == 0)
		{
			pat[npat*2+2] = last2[0]*ca - last2[1]*sa;
			pat[npat*2+3] = last2[0]*sa + last2[1]*ca;
			npat++;
		}
	}


	// Start sampling.
	float cr = vmax * (1.0f - m_params.velBias);
	float res[3];
	dtVset(res, dvel[0] * m_params.velBias, 0, dvel[2] * m_params.velBias);
	int ns = 0;

	for (int k = 0; k < depth; ++k)
	{
		float minPenalty = FLT_MAX;
		float bvel[3];
		dtVset(bvel, 0,0,0);
		
		for (int i = 0; i < npat; ++i)
		{
			float vcand[3];
			vcand[0] = res[0] + pat[i*2+0]*cr;
			vcand[1] = 0;
			vcand[2] = res[2] + pat[i*2+1]*cr;
			
			if (dtSqr(vcand[0])+dtSqr(vcand[2]) > dtSqr(vmax+0.001f)) continue;
			
			const float penalty = processSample(vcand,cr/10, pos,rad,vel,dvel, minPenalty, debug);
			ns++;
			if (penalty < minPenalty)
			{
//.........这里部分代码省略.........
开发者ID:RyunosukeOno,项目名称:rayjack,代码行数:101,代码来源:DetourObstacleAvoidance.cpp

示例13: run

 void run()
 {
     prepare();
     start();
     stop(Journal{});
 }
开发者ID:E-LLP,项目名称:rippled,代码行数:6,代码来源:Stoppable.test.cpp

示例14: qDebug

void AbstractDecorator::decorate(const QString &text, int state)
{
    if (text.contains("\n")) {
        qDebug() << "Wrong block found";
        return;
    }

    prepare(text);

    QmlJS::Scanner scanner;
    QList<QmlJS::Token> tokens = scanner(text, state);
    for (int i = 0; i < tokens.count(); i++) {
        const QmlJS::Token token = tokens.at(i);

        switch (token.kind) {
        case QmlJS::Token::Keyword:
            addKeyword(token.offset, token.length);
            break;
        case QmlJS::Token::Identifier: {
                QString entry = text.mid(token.offset, token.length);

                if (maybeQmlKeyword(entry)) {
                    // check the previous token
                    if (i == 0 || tokens.at(i - 1).isNot(QmlJS::Token::Dot)) {
                        if (i + 1 == tokens.count() || tokens.at(i + 1).isNot(QmlJS::Token::Colon)) {
                            addKeyword(token.offset, token.length);
                            break;
                        }
                    }
                } else if (i > 0 && maybeQmlBuiltinType(entry)) {
                    const QmlJS::Token &previousToken = tokens.at(i - 1);
                    if (previousToken.is(QmlJS::Token::Identifier)
                        && text.mid(previousToken.offset, previousToken.length) == QLatin1String("property")) {
                        addKeyword(token.offset, token.length);
                        break;
                    }
                }

                if (maybeMacro(entry)) {
                    addMacro(token.offset, token.length);
                    break;
                }

                if (entry.at(0).isUpper()) {
                    // Check if we are importing a module
                    if (i > 0) {
                        const QmlJS::Token &previousToken = tokens.first();
                        if (previousToken.is(QmlJS::Token::Identifier)
                            && text.mid(previousToken.offset, previousToken.length) == QLatin1String("import")) {
                            addKeyword(token.offset, token.length);
                            break;
                        }
                    }

                    addComponent(token.offset, token.length);
                    break;
                }

                // Try to find if it is a property
                // The easy ones are followed by a { or a :
                if (i + 1 < tokens.count()) {
                    const QmlJS::Token &nextToken = tokens.at(i + 1);
                    if (nextToken.is(QmlJS::Token::Colon)
                        || nextToken.is(QmlJS::Token::LeftBrace)) {
                        addIdentifier(token.offset, token.length);
                        break;
                    }
                }

                // A harder one is anchors.fill:
                if (i + 3 < tokens.count()) {
                    const QmlJS::Token &next1Token = tokens.at(i + 1);
                    const QmlJS::Token &next2Token = tokens.at(i + 2);
                    const QmlJS::Token &next3Token = tokens.at(i + 3);

                    if (next1Token.is(QmlJS::Token::Dot)
                        && next2Token.is(QmlJS::Token::Identifier)
                        && (next3Token.is(QmlJS::Token::Colon)
                            || next3Token.is(QmlJS::Token::LeftBrace))) {
                        addIdentifier(token.offset, token.length);
                        break;
                    }
                }
            }
            break;
        case QmlJS::Token::String:
            addString(token.offset, token.length);
            break;
        case QmlJS::Token::Comment:
            addComment(token.offset, token.length);
            break;
        case QmlJS::Token::Number:
            addNumber(token.offset, token.length);
            break;
        default:
            break;
        }
    }

    setState(scanner.state());
//.........这里部分代码省略.........
开发者ID:SfietKonstantin,项目名称:libqmldecorator,代码行数:101,代码来源:abstractdecorator.cpp

示例15: uassertStatusOK

    long long DeleteExecutor::execute(OperationContext* txn, Database* db) {
        uassertStatusOK(prepare());
        uassert(17417,
                mongoutils::str::stream() <<
                "DeleteExecutor::prepare() failed to parse query " << _request->getQuery(),
                _isQueryParsed);
        const bool logop = _request->shouldCallLogOp();
        const NamespaceString& ns(_request->getNamespaceString());
        if (!_request->isGod()) {
            if (ns.isSystem()) {
                uassert(12050,
                        "cannot delete from system namespace",
                        legalClientSystemNS(ns.ns(), true));
            }
            if (ns.ns().find('$') != string::npos) {
                log() << "cannot delete from collection with reserved $ in name: " << ns << endl;
                uasserted( 10100, "cannot delete from collection with reserved $ in name" );
            }
        }

        Collection* collection = db->getCollection(txn, ns.ns());
        if (NULL == collection) {
            return 0;
        }

        uassert(10101,
                str::stream() << "cannot remove from a capped collection: " << ns.ns(),
                !collection->isCapped());

        uassert(ErrorCodes::NotMaster,
                str::stream() << "Not primary while removing from " << ns.ns(),
                !logop ||
                repl::getGlobalReplicationCoordinator()->canAcceptWritesForDatabase(ns.db()));

        long long nDeleted = 0;

        Runner* rawRunner;
        if (_canonicalQuery.get()) {
            uassertStatusOK(getRunner(txn, collection, _canonicalQuery.release(), &rawRunner));
        }
        else {
            CanonicalQuery* ignored;
            uassertStatusOK(getRunner(txn,
                                      collection,
                                      ns.ns(),
                                      _request->getQuery(),
                                      &rawRunner,
                                      &ignored));
        }

        auto_ptr<Runner> runner(rawRunner);
        ScopedRunnerRegistration safety(runner.get());

        DiskLoc rloc;
        Runner::RunnerState state;
        CurOp* curOp = txn->getCurOp();
        int oldYieldCount = curOp->numYields();
        while (Runner::RUNNER_ADVANCED == (state = runner->getNext(NULL, &rloc))) {
            if (oldYieldCount != curOp->numYields()) {
                uassert(ErrorCodes::NotMaster,
                        str::stream() << "No longer primary while removing from " << ns.ns(),
                        !logop ||
                        repl::getGlobalReplicationCoordinator()->canAcceptWritesForDatabase(
                                ns.db()));
                oldYieldCount = curOp->numYields();
            }
            BSONObj toDelete;

            // TODO: do we want to buffer docs and delete them in a group rather than
            // saving/restoring state repeatedly?
            runner->saveState();
            collection->deleteDocument(txn, rloc, false, false, logop ? &toDelete : NULL );
            runner->restoreState(txn);

            nDeleted++;

            if (logop) {
                if ( toDelete.isEmpty() ) {
                    log() << "Deleted object without id in collection " << collection->ns()
                          << ", not logging.";
                }
                else {
                    bool replJustOne = true;
                    repl::logOp(txn, "d", ns.ns().c_str(), toDelete, 0, &replJustOne);
                }
            }

            if (!_request->isMulti()) {
                break;
            }

            if (!_request->isGod()) {
                txn->recoveryUnit()->commitIfNeeded();
            }

            if (debug && _request->isGod() && nDeleted == 100) {
                log() << "warning high number of deletes with god=true "
                      << " which could use significant memory b/c we don't commit journal";
            }
        }
//.........这里部分代码省略.........
开发者ID:MohdVara,项目名称:mongo,代码行数:101,代码来源:delete_executor.cpp


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