本文整理汇总了C++中cc函数的典型用法代码示例。如果您正苦于以下问题:C++ cc函数的具体用法?C++ cc怎么用?C++ cc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了cc函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: _handlePossibleShardedMessage
bool _handlePossibleShardedMessage( Message &m, DbResponse* dbresponse ) {
DEV verify( shardingState.enabled() );
int op = m.operation();
if ( op < 2000
|| op >= 3000
|| op == dbGetMore // cursors are weird
)
return false;
DbMessage d(m);
const char *ns = d.getns();
string errmsg;
// We don't care about the version here, since we're returning it later in the writeback
ConfigVersion received, wanted;
if ( shardVersionOk( ns , errmsg, received, wanted ) ) {
return false;
}
LOG(1) << "connection meta data too old - will retry ns:(" << ns << ") op:(" << opToString(op) << ") " << errmsg << endl;
if ( doesOpGetAResponse( op ) ) {
verify( dbresponse );
BufBuilder b( 32768 );
b.skip( sizeof( QueryResult ) );
{
BSONObj obj = BSON( "$err" << errmsg << "ns" << ns );
b.appendBuf( obj.objdata() , obj.objsize() );
}
QueryResult *qr = (QueryResult*)b.buf();
qr->_resultFlags() = ResultFlag_ErrSet | ResultFlag_ShardConfigStale;
qr->len = b.len();
qr->setOperation( opReply );
qr->cursorId = 0;
qr->startingFrom = 0;
qr->nReturned = 1;
b.decouple();
Message * resp = new Message();
resp->setData( qr , true );
dbresponse->response = resp;
dbresponse->responseTo = m.header()->id;
return true;
}
uassert( 9517 , "writeback" , ( d.reservedField() & DbMessage::Reserved_FromWriteback ) == 0 );
OID writebackID;
writebackID.init();
lastError.getSafe()->writeback( writebackID );
const OID& clientID = ShardedConnectionInfo::get(false)->getID();
massert( 10422 , "write with bad shard config and no server id!" , clientID.isSet() );
LOG(1) << "got write with an old config - writing back ns: " << ns << endl;
LOG(1) << m.toString() << endl;
BSONObjBuilder b;
b.appendBool( "writeBack" , true );
b.append( "ns" , ns );
b.append( "id" , writebackID );
b.append( "connectionId" , cc().getConnectionId() );
b.append( "instanceIdent" , prettyHostName() );
shardingState.getVersion( ns ).addToBSON( b );
ShardedConnectionInfo* info = ShardedConnectionInfo::get( false );
( info ? info->getVersion(ns) : ConfigVersion( 0, OID() ) ).addToBSON( b, "yourVersion" );
b.appendBinData( "msg" , m.header()->len , bdtCustom , (char*)(m.singleData()) );
LOG(2) << "writing back msg with len: " << m.header()->len << " op: " << m.operation() << endl;
writeBackManager.queueWriteBack( clientID.str() , b.obj() );
return true;
}
开发者ID:abhishekkumar1989,项目名称:mongo,代码行数:76,代码来源:d_logic.cpp
示例2: run
bool run(OperationContext* txn, const string& dbname,
BSONObj& cmdObj,
int,
string& errmsg,
BSONObjBuilder& result,
bool fromRepl ) {
//
// Correct behavior here is very finicky.
//
// 1. The first step is to append the error that occurred on the previous operation.
// This adds an "err" field to the command, which is *not* the command failing.
//
// 2. Next we parse and validate write concern options. If these options are invalid
// the command fails no matter what, even if we actually had an error earlier. The
// reason for checking here is to match legacy behavior on these kind of failures -
// we'll still get an "err" field for the write error.
//
// 3. If we had an error on the previous operation, we then return immediately.
//
// 4. Finally, we actually enforce the write concern. All errors *except* timeout are
// reported with ok : 0.0, to match legacy behavior.
//
// There is a special case when "wOpTime" and "wElectionId" are explicitly provided by
// the client (mongos) - in this case we *only* enforce the write concern if it is
// valid.
//
// We always need to either report "err" (if ok : 1) or "errmsg" (if ok : 0), even if
// err is null.
//
LastError *le = lastError.disableForCommand();
// Always append lastOp and connectionId
Client& c = cc();
c.appendLastOp( result );
// for sharding; also useful in general for debugging
result.appendNumber( "connectionId" , c.getConnectionId() );
OpTime lastOpTime;
BSONField<OpTime> wOpTimeField("wOpTime");
FieldParser::FieldState extracted = FieldParser::extract(cmdObj, wOpTimeField,
&lastOpTime, &errmsg);
if (!extracted) {
result.append("badGLE", cmdObj);
appendCommandStatus(result, false, errmsg);
return false;
}
bool lastOpTimePresent = extracted != FieldParser::FIELD_NONE;
if (!lastOpTimePresent) {
// Use the client opTime if no wOpTime is specified
lastOpTime = cc().getLastOp();
}
OID electionId;
BSONField<OID> wElectionIdField("wElectionId");
extracted = FieldParser::extract(cmdObj, wElectionIdField,
&electionId, &errmsg);
if (!extracted) {
result.append("badGLE", cmdObj);
appendCommandStatus(result, false, errmsg);
return false;
}
bool electionIdPresent = extracted != FieldParser::FIELD_NONE;
bool errorOccurred = false;
// Errors aren't reported when wOpTime is used
if ( !lastOpTimePresent ) {
if ( le->nPrev != 1 ) {
errorOccurred = LastError::noError.appendSelf( result, false );
le->appendSelfStatus( result );
}
else {
errorOccurred = le->appendSelf( result, false );
}
}
BSONObj writeConcernDoc = cmdObj;
// Use the default options if we have no gle options aside from wOpTime/wElectionId
const int nFields = cmdObj.nFields();
bool useDefaultGLEOptions = (nFields == 1) ||
(nFields == 2 && lastOpTimePresent) ||
(nFields == 3 && lastOpTimePresent && electionIdPresent);
if (useDefaultGLEOptions) {
BSONObj getLastErrorDefault =
repl::getGlobalReplicationCoordinator()->getGetLastErrorDefault();
if (!getLastErrorDefault.isEmpty()) {
writeConcernDoc = getLastErrorDefault;
}
}
//
// Validate write concern no matter what, this matches 2.4 behavior
//
WriteConcernOptions writeConcern;
Status status = writeConcern.parse( writeConcernDoc );
//.........这里部分代码省略.........
开发者ID:Benguang,项目名称:mongo,代码行数:101,代码来源:get_last_error.cpp
示例3: assembleResponse
// Returns false when request includes 'end'
void assembleResponse( Message &m, DbResponse &dbresponse, const HostAndPort& remote ) {
// before we lock...
int op = m.operation();
bool isCommand = false;
const char *ns = m.singleData()->_data + 4;
if ( op == dbQuery ) {
if( strstr(ns, ".$cmd") ) {
isCommand = true;
opwrite(m);
if( strstr(ns, ".$cmd.sys.") ) {
if( strstr(ns, "$cmd.sys.inprog") ) {
inProgCmd(m, dbresponse);
return;
}
if( strstr(ns, "$cmd.sys.killop") ) {
killOp(m, dbresponse);
return;
}
if( strstr(ns, "$cmd.sys.unlock") ) {
unlockFsync(ns, m, dbresponse);
return;
}
}
}
else {
opread(m);
}
}
else if( op == dbGetMore ) {
opread(m);
}
else {
opwrite(m);
}
globalOpCounters.gotOp( op , isCommand );
Client& c = cc();
if ( c.getAuthenticationInfo() )
c.getAuthenticationInfo()->startRequest();
auto_ptr<CurOp> nestedOp;
CurOp* currentOpP = c.curop();
if ( currentOpP->active() ) {
nestedOp.reset( new CurOp( &c , currentOpP ) );
currentOpP = nestedOp.get();
}
else {
c.newTopLevelRequest();
}
CurOp& currentOp = *currentOpP;
currentOp.reset(remote,op);
OpDebug& debug = currentOp.debug();
debug.op = op;
long long logThreshold = cmdLine.slowMS;
bool shouldLog = logLevel >= 1;
if ( op == dbQuery ) {
if ( handlePossibleShardedMessage( m , &dbresponse ) )
return;
receivedQuery(c , dbresponse, m );
}
else if ( op == dbGetMore ) {
if ( ! receivedGetMore(dbresponse, m, currentOp) )
shouldLog = true;
}
else if ( op == dbMsg ) {
// deprecated - replaced by commands
char *p = m.singleData()->_data;
int len = strlen(p);
if ( len > 400 )
out() << curTimeMillis64() % 10000 <<
" long msg received, len:" << len << endl;
Message *resp = new Message();
if ( strcmp( "end" , p ) == 0 )
resp->setData( opReply , "dbMsg end no longer supported" );
else
resp->setData( opReply , "i am fine - dbMsg deprecated");
dbresponse.response = resp;
dbresponse.responseTo = m.header()->id;
}
else {
try {
const NamespaceString nsString( ns );
// The following operations all require authorization.
// dbInsert, dbUpdate and dbDelete can be easily pre-authorized,
// here, but dbKillCursors cannot.
if ( op == dbKillCursors ) {
currentOp.ensureStarted();
logThreshold = 10;
receivedKillCursors(m);
//.........这里部分代码省略.........
开发者ID:JKO,项目名称:mongo,代码行数:101,代码来源:instance.cpp
示例4: runNoDirectClient
bool runNoDirectClient( const string& ns ,
const BSONObj& queryOriginal , const BSONObj& fields , const BSONObj& update ,
bool upsert , bool returnNew , bool remove ,
BSONObjBuilder& result ) {
Lock::DBWrite lk( ns );
Client::Context cx( ns );
BSONObj doc;
bool found = Helpers::findOne( ns.c_str() , queryOriginal , doc );
BSONObj queryModified = queryOriginal;
if ( found && doc["_id"].type() && ! isSimpleIdQuery( queryOriginal ) ) {
// we're going to re-write the query to be more efficient
// we have to be a little careful because of positional operators
// maybe we can pass this all through eventually, but right now isn't an easy way
BSONObjBuilder b( queryOriginal.objsize() + 10 );
b.append( doc["_id"] );
bool addedAtomic = false;
BSONObjIterator i( queryOriginal );
while ( i.more() ) {
const BSONElement& elem = i.next();
if ( str::equals( "_id" , elem.fieldName() ) ) {
// we already do _id
continue;
}
if ( ! str::contains( elem.fieldName() , '.' ) ) {
// if there is a dotted field, accept we may need more query parts
continue;
}
if ( ! addedAtomic ) {
b.appendBool( "$atomic" , true );
addedAtomic = true;
}
b.append( elem );
}
queryModified = b.obj();
}
if ( remove ) {
_appendHelper( result , doc , found , fields );
if ( found ) {
deleteObjects( ns.c_str() , queryModified , true , true );
BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
le.appendNumber( "n" , 1 );
le.done();
}
}
else {
// update
if ( ! found && ! upsert ) {
// didn't have it, and am not upserting
_appendHelper( result , doc , found , fields );
}
else {
// we found it or we're updating
if ( ! returnNew ) {
_appendHelper( result , doc , found , fields );
}
UpdateResult res = updateObjects( ns.c_str() , update , queryModified , upsert , false , true , cc().curop()->debug() );
if ( returnNew ) {
if ( ! res.existing && res.upserted.isSet() ) {
queryModified = BSON( "_id" << res.upserted );
}
log() << "queryModified: " << queryModified << endl;
verify( Helpers::findOne( ns.c_str() , queryModified , doc ) );
_appendHelper( result , doc , true , fields );
}
BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
le.appendBool( "updatedExisting" , res.existing );
le.appendNumber( "n" , res.num );
if ( res.upserted.isSet() )
le.append( "upserted" , res.upserted );
le.done();
}
}
return true;
}
开发者ID:89snake89,项目名称:mongo,代码行数:92,代码来源:find_and_modify.cpp
示例5: assembleResponse
// Returns false when request includes 'end'
bool assembleResponse( Message &m, DbResponse &dbresponse, const SockAddr &client ) {
// before we lock...
int op = m.operation();
bool isCommand = false;
const char *ns = m.singleData()->_data + 4;
if ( op == dbQuery ) {
if( strstr(ns, ".$cmd") ) {
isCommand = true;
opwrite(m);
if( strstr(ns, ".$cmd.sys.") ) {
if( strstr(ns, "$cmd.sys.inprog") ) {
inProgCmd(m, dbresponse);
return true;
}
if( strstr(ns, "$cmd.sys.killop") ) {
killOp(m, dbresponse);
return true;
}
if( strstr(ns, "$cmd.sys.unlock") ) {
unlockFsync(ns, m, dbresponse);
return true;
}
}
}
else {
opread(m);
}
}
else if( op == dbGetMore ) {
opread(m);
}
else {
opwrite(m);
}
globalOpCounters.gotOp( op , isCommand );
Client& c = cc();
auto_ptr<CurOp> nestedOp;
CurOp* currentOpP = c.curop();
if ( currentOpP->active() ){
nestedOp.reset( new CurOp( &c , currentOpP ) );
currentOpP = nestedOp.get();
}
CurOp& currentOp = *currentOpP;
currentOp.reset(client,op);
OpDebug& debug = currentOp.debug();
StringBuilder& ss = debug.str;
ss << opToString( op ) << " ";
int logThreshold = cmdLine.slowMS;
bool log = logLevel >= 1;
if ( op == dbQuery ) {
if ( handlePossibleShardedMessage( m , &dbresponse ) )
return true;
receivedQuery(c , dbresponse, m );
}
else if ( op == dbGetMore ) {
if ( ! receivedGetMore(dbresponse, m, currentOp) )
log = true;
}
else if ( op == dbMsg ) {
// deprecated - replaced by commands
char *p = m.singleData()->_data;
int len = strlen(p);
if ( len > 400 )
out() << curTimeMillis() % 10000 <<
" long msg received, len:" << len << endl;
Message *resp = new Message();
if ( strcmp( "end" , p ) == 0 )
resp->setData( opReply , "dbMsg end no longer supported" );
else
resp->setData( opReply , "i am fine - dbMsg deprecated");
dbresponse.response = resp;
dbresponse.responseTo = m.header()->id;
}
else {
const char *ns = m.singleData()->_data + 4;
char cl[256];
nsToDatabase(ns, cl);
if( ! c.getAuthenticationInfo()->isAuthorized(cl) ) {
uassert_nothrow("unauthorized");
}
else {
try {
if ( op == dbInsert ) {
receivedInsert(m, currentOp);
}
else if ( op == dbUpdate ) {
receivedUpdate(m, currentOp);
}
else if ( op == dbDelete ) {
receivedDelete(m, currentOp);
//.........这里部分代码省略.........
开发者ID:sivy,项目名称:mongo,代码行数:101,代码来源:instance.cpp
示例6: lock
/* must call this on a delete so we clean up the cursors. */
void ClientCursor::aboutToDelete(const DiskLoc& dl) {
recursive_scoped_lock lock(ccmutex);
Database *db = cc().database();
verify(db);
aboutToDeleteForSharding( db , dl );
CCByLoc& bl = db->ccByLoc;
CCByLoc::iterator j = bl.lower_bound(ByLocKey::min(dl));
CCByLoc::iterator stop = bl.upper_bound(ByLocKey::max(dl));
if ( j == stop )
return;
vector<ClientCursor*> toAdvance;
while ( 1 ) {
toAdvance.push_back(j->second);
DEV verify( j->first.loc == dl );
++j;
if ( j == stop )
break;
}
if( toAdvance.size() >= 3000 ) {
log() << "perf warning MPW101: " << toAdvance.size() << " cursors for one diskloc "
<< dl.toString()
<< ' ' << toAdvance[1000]->_ns
<< ' ' << toAdvance[2000]->_ns
<< ' ' << toAdvance[1000]->_pinValue
<< ' ' << toAdvance[2000]->_pinValue
<< ' ' << toAdvance[1000]->_pos
<< ' ' << toAdvance[2000]->_pos
<< ' ' << toAdvance[1000]->_idleAgeMillis
<< ' ' << toAdvance[2000]->_idleAgeMillis
<< ' ' << toAdvance[1000]->_doingDeletes
<< ' ' << toAdvance[2000]->_doingDeletes
<< endl;
//wassert( toAdvance.size() < 5000 );
}
for ( vector<ClientCursor*>::iterator i = toAdvance.begin(); i != toAdvance.end(); ++i ) {
ClientCursor* cc = *i;
wassert(cc->_db == db);
if ( cc->_doingDeletes ) continue;
Cursor *c = cc->_c.get();
if ( c->capped() ) {
/* note we cannot advance here. if this condition occurs, writes to the oplog
have "caught" the reader. skipping ahead, the reader would miss postentially
important data.
*/
delete cc;
continue;
}
c->recoverFromYield();
DiskLoc tmp1 = c->refLoc();
if ( tmp1 != dl ) {
// This might indicate a failure to call ClientCursor::prepareToYield() but it can
// also happen during correct operation, see SERVER-2009.
problem() << "warning: cursor loc " << tmp1 << " does not match byLoc position " << dl << " !" << endl;
}
else {
c->advance();
}
while (!c->eof() && c->refLoc() == dl) {
/* We don't delete at EOF because we want to return "no more results" rather than "no such cursor".
* The loop is to handle MultiKey indexes where the deleted record is pointed to by multiple adjacent keys.
* In that case we need to advance until we get to the next distinct record or EOF.
* SERVER-4154
*/
c->advance();
}
cc->updateLocation();
}
}
开发者ID:matulef,项目名称:mongo,代码行数:79,代码来源:clientcursor.cpp
示例7: Exception
Exception(const Location &where, const T &detail):
Preprocessor::Exception(where, cc("formatter error: ", detail))
{
}
开发者ID:el-bart,项目名称:ACARM-ng,代码行数:4,代码来源:Exception.hpp
示例8: _isAuthorizedSpecialChecks
bool AuthenticationInfo::_isAuthorizedSpecialChecks( const string& dbname ) const {
if ( cc().isGod() )
return true;
return _isLocalHostAndLocalHostIsAuthorizedForAll;
}
开发者ID:nosqldb,项目名称:mongo,代码行数:5,代码来源:security.cpp
示例9: cc
void Lock::ScopedLock::recordTime() {
if (haveClient()) {
cc().curop()->lockStat().recordLockTimeMicros(_type, _timer.micros());
}
}
开发者ID:TylerBrock,项目名称:mongo,代码行数:5,代码来源:d_concurrency.cpp
示例10: getCurrentScene
bool NxuPhysicsExport::Write(NxJoint *j,const char *userProperties,const char *id)
{
bool ret = false;
NxSceneDesc *current = getCurrentScene();
CustomCopy cc(mCollection,current);
NxJointDesc *joint = 0;
switch ( j->getType() )
{
case NX_JOINT_PRISMATIC:
if ( 1 )
{
::NxPrismaticJointDesc d1;
NxPrismaticJoint *sj = j->isPrismaticJoint();
sj->saveToDesc(d1);
addActor( d1.actor[0] );
addActor( d1.actor[1] );
NxPrismaticJointDesc *desc = new NxPrismaticJointDesc;
desc->copyFrom(d1,cc);
joint = static_cast<NxJointDesc *>(desc);
}
break;
case NX_JOINT_REVOLUTE:
if ( 1 )
{
::NxRevoluteJointDesc d1;
NxRevoluteJoint *sj = j->isRevoluteJoint();
sj->saveToDesc(d1);
addActor( d1.actor[0] );
addActor( d1.actor[1] );
NxRevoluteJointDesc *desc = new NxRevoluteJointDesc;
desc->copyFrom(d1,cc);
joint = static_cast<NxJointDesc *>(desc);
}
break;
case NX_JOINT_CYLINDRICAL:
if ( 1 )
{
::NxCylindricalJointDesc d1;
NxCylindricalJoint *sj = j->isCylindricalJoint();
sj->saveToDesc(d1);
addActor( d1.actor[0] );
addActor( d1.actor[1] );
NxCylindricalJointDesc *desc = new NxCylindricalJointDesc;
desc->copyFrom(d1,cc);
joint = static_cast<NxJointDesc *>(desc);
}
break;
case NX_JOINT_SPHERICAL:
if ( 1 )
{
::NxSphericalJointDesc d1;
NxSphericalJoint *sj = j->isSphericalJoint();
sj->saveToDesc(d1);
addActor( d1.actor[0] );
addActor( d1.actor[1] );
NxSphericalJointDesc *desc = new NxSphericalJointDesc;
desc->copyFrom(d1,cc);
joint = static_cast<NxJointDesc *>(desc);
}
break;
case NX_JOINT_POINT_ON_LINE:
if ( 1 )
{
::NxPointOnLineJointDesc d1;
NxPointOnLineJoint *sj = j->isPointOnLineJoint();
sj->saveToDesc(d1);
addActor( d1.actor[0] );
addActor( d1.actor[1] );
NxPointOnLineJointDesc *desc = new NxPointOnLineJointDesc;
desc->copyFrom(d1,cc);
joint = static_cast<NxJointDesc *>(desc);
}
break;
case NX_JOINT_POINT_IN_PLANE:
if ( 1 )
{
::NxPointInPlaneJointDesc d1;
NxPointInPlaneJoint *sj = j->isPointInPlaneJoint();
sj->saveToDesc(d1);
addActor( d1.actor[0] );
addActor( d1.actor[1] );
NxPointInPlaneJointDesc *desc = new NxPointInPlaneJointDesc;
desc->copyFrom(d1,cc);
joint = static_cast<NxJointDesc *>(desc);
}
break;
case NX_JOINT_DISTANCE:
if ( 1 )
{
::NxDistanceJointDesc d1;
NxDistanceJoint *sj = j->isDistanceJoint();
sj->saveToDesc(d1);
addActor( d1.actor[0] );
addActor( d1.actor[1] );
NxDistanceJointDesc *desc = new NxDistanceJointDesc;
desc->copyFrom(d1,cc);
//.........这里部分代码省略.........
开发者ID:daher-alfawares,项目名称:xr.desktop,代码行数:101,代码来源:NXU_PhysicsExport.cpp
示例11: cc
bool CmdLogout::run(const string& dbname , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
AuthenticationInfo *ai = cc().getAuthenticationInfo();
ai->logout(dbname);
return true;
}
开发者ID:nosqldb,项目名称:mongo,代码行数:5,代码来源:security.cpp
示例12: getRunner
/**
* For a given query, get a runner. The runner could be a SingleSolutionRunner, a
* CachedQueryRunner, or a MultiPlanRunner, depending on the cache/query solver/etc.
*/
Status getRunner(CanonicalQuery* rawCanonicalQuery, Runner** out, size_t plannerOptions) {
verify(rawCanonicalQuery);
auto_ptr<CanonicalQuery> canonicalQuery(rawCanonicalQuery);
// Try to look up a cached solution for the query.
// TODO: Can the cache have negative data about a solution?
PlanCache* localCache = PlanCache::get(canonicalQuery->ns());
if (NULL != localCache) {
CachedSolution* cs = localCache->get(*canonicalQuery);
if (NULL != cs) {
// We have a cached solution. Hand the canonical query and cached solution off to
// the cached plan runner, which takes ownership of both.
WorkingSet* ws;
PlanStage* root;
verify(StageBuilder::build(*cs->solution, &root, &ws));
*out = new CachedPlanRunner(canonicalQuery.release(), cs, root, ws);
return Status::OK();
}
}
// No entry in cache for the query. We have to solve the query ourself.
// Get the indices that we could possibly use.
Database* db = cc().database();
verify( db );
Collection* collection = db->getCollection( canonicalQuery->ns() );
// This can happen as we're called by internal clients as well.
if (NULL == collection) {
const string& ns = canonicalQuery->ns();
*out = new EOFRunner(canonicalQuery.release(), ns);
return Status::OK();
}
// If we have an _id index we can use the idhack runner.
if (canUseIDHack(*canonicalQuery) && collection->getIndexCatalog()->findIdIndex()) {
*out = new IDHackRunner(collection, canonicalQuery.release());
return Status::OK();
}
// If it's not NULL, we may have indices. Access the catalog and fill out IndexEntry(s)
QueryPlannerParams plannerParams;
for (int i = 0; i < collection->getIndexCatalog()->numIndexesReady(); ++i) {
IndexDescriptor* desc = collection->getIndexCatalog()->getDescriptor( i );
plannerParams.indices.push_back(IndexEntry(desc->keyPattern(),
desc->isMultikey(),
desc->isSparse(),
desc->indexName()));
}
// Tailable: If the query requests tailable the collection must be capped.
if (canonicalQuery->getParsed().hasOption(QueryOption_CursorTailable)) {
if (!collection->isCapped()) {
return Status(ErrorCodes::BadValue,
"tailable cursor requested on non capped collection");
}
// If a sort is specified it must be equal to expectedSort.
const BSONObj expectedSort = BSON("$natural" << 1);
const BSONObj& actualSort = canonicalQuery->getParsed().getSort();
if (!actualSort.isEmpty() && !(actualSort == expectedSort)) {
return Status(ErrorCodes::BadValue,
"invalid sort specified for tailable cursor: "
+ actualSort.toString());
}
}
// Process the planning options.
plannerParams.options = plannerOptions;
if (storageGlobalParams.noTableScan) {
const string& ns = canonicalQuery->ns();
// There are certain cases where we ignore this restriction:
bool ignore = canonicalQuery->getQueryObj().isEmpty()
|| (string::npos != ns.find(".system."))
|| (0 == ns.find("local."));
if (!ignore) {
plannerParams.options |= QueryPlannerParams::NO_TABLE_SCAN;
}
}
if (!(plannerParams.options & QueryPlannerParams::NO_TABLE_SCAN)) {
plannerParams.options |= QueryPlannerParams::INCLUDE_COLLSCAN;
}
// If the caller wants a shard filter, make sure we're actually sharded.
if (plannerParams.options & QueryPlannerParams::INCLUDE_SHARD_FILTER) {
CollectionMetadataPtr collMetadata = shardingState.getCollectionMetadata(canonicalQuery->ns());
if (collMetadata) {
plannerParams.shardKey = collMetadata->getKeyPattern();
}
else {
// If there's no metadata don't bother w/the shard filter since we won't know what
// the key pattern is anyway...
plannerParams.options &= ~QueryPlannerParams::INCLUDE_SHARD_FILTER;
}
}
//.........这里部分代码省略.........
开发者ID:gabrielhao,项目名称:mongo,代码行数:101,代码来源:get_runner.cpp
示例13: dassert
bool WriteCmd::run(const string& dbName,
BSONObj& cmdObj,
int options,
string& errMsg,
BSONObjBuilder& result,
bool fromRepl) {
// Can't be run on secondaries (logTheOp() == false, slaveOk() == false).
dassert( !fromRepl );
BatchedCommandRequest request( _writeType );
BatchedCommandResponse response;
if ( !request.parseBSON( cmdObj, &errMsg ) || !request.isValid( &errMsg ) ) {
// Batch parse failure
response.setOk( false );
response.setN( 0 );
response.setErrCode( ErrorCodes::FailedToParse );
response.setErrMessage( errMsg );
dassert( response.isValid( &errMsg ) );
result.appendElements( response.toBSON() );
// TODO
// There's a pending issue about how to report response here. If we use
// the command infra-structure, we should reuse the 'errmsg' field. But
// we have already filed that message inside the BatchCommandResponse.
// return response.getOk();
return true;
}
// Note that this is a runCommmand, and therefore, the database and the collection name
// are in different parts of the grammar for the command. But it's more convenient to
// work with a NamespaceString. We built it here and replace it in the parsed command.
// Internally, everything work with the namespace string as opposed to just the
// collection name.
NamespaceString nss(dbName, request.getNS());
request.setNS(nss.ns());
Status status = userAllowedWriteNS( nss );
if ( !status.isOK() )
return appendCommandStatus( result, status );
if ( cc().curop() )
cc().curop()->setNS( nss.ns() );
if ( request.getBatchType() == BatchedCommandRequest::BatchType_Insert ) {
// check all docs
BatchedInsertRequest* insertRequest = request.getInsertRequest();
vector<BSONObj>& docsToInsert = insertRequest->getDocuments();
for ( size_t i = 0; i < docsToInsert.size(); i++ ) {
StatusWith<BSONObj> fixed = fixDocumentForInsert( docsToInsert[i] );
if ( !fixed.isOK() ) {
// we don't return early since each doc can be handled independantly
continue;
}
if ( fixed.getValue().isEmpty() ) {
continue;
}
docsToInsert[i] = fixed.getValue();
}
}
BSONObj defaultWriteConcern;
// This is really bad - it's only safe because we leak the defaults by overriding them with
// new defaults and because we never reset to an empty default.
// TODO: fix this for sane behavior where we query repl set object
if ( getLastErrorDefault ) defaultWriteConcern = *getLastErrorDefault;
if ( defaultWriteConcern.isEmpty() ) {
BSONObjBuilder b;
b.append( "w", 1 );
defaultWriteConcern = b.obj();
}
WriteBatchExecutor writeBatchExecutor(defaultWriteConcern,
&cc(),
&globalOpCounters,
lastError.get());
writeBatchExecutor.executeBatch( request, &response );
result.appendElements( response.toBSON() );
// TODO
// There's a pending issue about how to report response here. If we use
// the command infra-structure, we should reuse the 'errmsg' field. But
// we have already filed that message inside the BatchCommandResponse.
// return response.getOk();
return true;
}
开发者ID:basukaladagi,项目名称:mongo,代码行数:90,代码来源:write_commands.cpp
示例14: runNoDirectClient
//.........这里部分代码省略.........
if ( str::contains( j.next().fieldName(), ".$" ) ) {
hasPositionalUpdate = true;
break;
}
}
}
}
BSONObjBuilder b( queryOriginal.objsize() + 10 );
b.append( doc["_id"] );
bool addedAtomic = false;
BSONObjIterator i( queryOriginal );
while ( i.more() ) {
const BSONElement& elem = i.next();
if ( str::equals( "_id" , elem.fieldName() ) ) {
// we already do _id
continue;
}
if ( ! hasPositionalUpdate ) {
// if there is a dotted field, accept we may need more query parts
continue;
}
if ( ! addedAtomic ) {
b.appendBool( "$atomic" , true );
addedAtomic = true;
}
b.append( elem );
}
queryModified = b.obj();
}
if ( remove ) {
_appendHelper( result , doc , found , fields );
if ( found ) {
deleteObjects( ns.c_str() , queryModified , true , true );
BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
le.appendNumber( "n" , 1 );
le.done();
}
}
else {
// update
if ( ! found && ! upsert ) {
// didn't have it, and am not upserting
_appendHelper( result , doc , found , fields );
}
else {
// we found it or we're updating
if ( ! returnNew ) {
_appendHelper( result , doc , found , fields );
}
const NamespaceString requestNs(ns);
UpdateRequest request(requestNs);
request.setQuery(queryModified);
request.setUpdates(update);
request.setUpsert(upsert);
request.setUpdateOpLog();
UpdateResult res = mongo::update(request, &cc().curop()->debug());
if ( returnNew ) {
if ( res.upserted.isSet() ) {
queryModified = BSON( "_id" << res.upserted );
}
else if ( queryModified["_id"].type() ) {
// we do this so that if the update changes the fields, it still matches
queryModified = queryModified["_id"].wrap();
}
if ( ! Helpers::findOne( ns.c_str() , queryModified , doc ) ) {
errmsg = str::stream() << "can't find object after modification "
<< " ns: " << ns
<< " queryModified: " << queryModified
<< " queryOriginal: " << queryOriginal;
log() << errmsg << endl;
return false;
}
_appendHelper( result , doc , true , fields );
}
BSONObjBuilder le( result.subobjStart( "lastErrorObject" ) );
le.appendBool( "updatedExisting" , res.existing );
le.appendNumber( "n" , res.numMatched );
if ( res.upserted.isSet() )
le.append( "upserted" , res.upserted );
le.done();
}
}
return true;
}
开发者ID:ChowZenki,项目名称:mongo,代码行数:101,代码来源:find_and_modify.cpp
示例15: invariant
std::unique_ptr<OperationContext> ServiceContextMongoD::_newOpCtx(Client* client) {
invariant(&cc() == client);
return stdx::make_unique<OperationContextImpl>();
}
开发者ID:stevelyall,项目名称:mongol-db,代码行数:4,代码来源:service_context_d.cpp
示例16: run
bool run(const string& dbname, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl ) {
Timer t;
string ns = dbname + '.' + cmdObj.firstElement().valuestr();
string key = cmdObj["key"].valuestrsafe();
BSONObj keyPattern = BSON( key << 1 );
BSONObj query = getQuery( cmdObj );
int bufSize = BSONObjMaxUserSize - 4096;
BufBuilder bb( bufSize );
char * start = bb.buf();
BSONArrayBuilder arr( bb );
BSONElementSet values;
long long nscanned = 0; // locations looked at
long long nscannedObjects = 0; // full objects looked at
long long n = 0; // matches
MatchDetails md;
NamespaceDetails * d = nsdetails( ns );
if ( ! d ) {
result.appendArray( "values" , BSONObj() );
result.append( "stats" , BSON( "n" << 0 << "nscanned" << 0 << "nscannedObjects" << 0 ) );
return true;
}
shared_ptr<Cursor> cursor;
if ( ! query.isEmpty() ) {
cursor = getOptimizedCursor( ns.c_str(), query, BSONObj() );
}
else {
// query is empty, so lets see if we can find an index
// with the key so we don't have to hit the raw data
NamespaceDetails::IndexIterator ii = d->ii();
while ( ii.more() ) {
IndexDetails& idx = ii.next();
if ( d->isMultikey( ii.pos() - 1 ) )
continue;
if ( idx.inKeyPattern( key ) ) {
cursor = getBestGuessCursor( ns.c_str(), BSONObj(), idx.keyPattern() );
if( cursor.get() ) break;
}
}
if ( ! cursor.get() )
|
请发表评论