本文整理汇总了C++中BSONElement::timestamp方法的典型用法代码示例。如果您正苦于以下问题:C++ BSONElement::timestamp方法的具体用法?C++ BSONElement::timestamp怎么用?C++ BSONElement::timestamp使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BSONElement
的用法示例。
在下文中一共展示了BSONElement::timestamp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: typeName
StatusWith<OpTime> ReplicationCoordinatorExternalStateImpl::loadLastOpTime(
OperationContext* txn) {
// TODO: handle WriteConflictExceptions below
try {
BSONObj oplogEntry;
if (!Helpers::getLast(txn, rsOplogName.c_str(), oplogEntry)) {
return StatusWith<OpTime>(
ErrorCodes::NoMatchingDocument,
str::stream() << "Did not find any entries in " << rsOplogName);
}
BSONElement tsElement = oplogEntry[tsFieldName];
if (tsElement.eoo()) {
return StatusWith<OpTime>(
ErrorCodes::NoSuchKey,
str::stream() << "Most recent entry in " << rsOplogName << " missing \"" <<
tsFieldName << "\" field");
}
if (tsElement.type() != bsonTimestamp) {
return StatusWith<OpTime>(
ErrorCodes::TypeMismatch,
str::stream() << "Expected type of \"" << tsFieldName <<
"\" in most recent " << rsOplogName <<
" entry to have type Timestamp, but found " << typeName(tsElement.type()));
}
// TODO(siyuan) add term
return StatusWith<OpTime>(OpTime(tsElement.timestamp(), 0));
}
catch (const DBException& ex) {
return StatusWith<OpTime>(ex.toStatus());
}
}
示例2: bsonExtractTimestampField
Status bsonExtractTimestampField(const BSONObj& object, StringData fieldName, Timestamp* out) {
BSONElement element;
Status status = bsonExtractTypedField(object, fieldName, bsonTimestamp, &element);
if (status.isOK())
*out = element.timestamp();
return status;
}
示例3: Status
StatusWith<ShardingMetadata> ShardingMetadata::readFromMetadata(const BSONObj& metadataObj) {
BSONElement smElem;
auto smExtractStatus =
bsonExtractTypedField(metadataObj, kGLEStatsFieldName, mongo::Object, &smElem);
if (!smExtractStatus.isOK()) {
return smExtractStatus;
}
if (smElem.embeddedObject().nFields() != 2) {
return Status(ErrorCodes::InvalidOptions,
str::stream() << "The $gleStats object can only have 2 fields, but got "
<< smElem.embeddedObject().toString());
}
BSONElement lastOpTimeElem;
auto lastOpTimeExtractStatus = bsonExtractTypedField(smElem.embeddedObject(),
kGLEStatsLastOpTimeFieldName,
mongo::bsonTimestamp,
&lastOpTimeElem);
if (!lastOpTimeExtractStatus.isOK()) {
return lastOpTimeExtractStatus;
}
BSONElement lastElectionIdElem;
auto lastElectionIdExtractStatus = bsonExtractTypedField(
smElem.embeddedObject(), kGLEStatsElectionIdFieldName, mongo::jstOID, &lastElectionIdElem);
if (!lastElectionIdExtractStatus.isOK()) {
return lastElectionIdExtractStatus;
}
return ShardingMetadata(lastOpTimeElem.timestamp(), lastElectionIdElem.OID());
}
示例4: invariant
/**
* data and len must be the arguments from RecordStore::insert() on an oplog collection.
*/
StatusWith<RecordId> extractKey(const char* data, int len) {
DEV invariant(validateBSON(data, len).isOK());
const BSONObj obj(data);
const BSONElement elem = obj["ts"];
if (elem.eoo())
return StatusWith<RecordId>(ErrorCodes::BadValue, "no ts field");
if (elem.type() != bsonTimestamp)
return StatusWith<RecordId>(ErrorCodes::BadValue, "ts must be a Timestamp");
return keyForOptime(elem.timestamp());
}
示例5: invariant
/**
* data and len must be the arguments from RecordStore::insert() on an oplog collection.
*/
StatusWith<RecordId> extractKey(const char* data, int len) {
// Use the latest BSON validation version. Oplog entries are allowed to contain decimal data
// even if decimal is disabled.
DEV invariant(validateBSON(data, len, BSONVersion::kLatest).isOK());
const BSONObj obj(data);
const BSONElement elem = obj["ts"];
if (elem.eoo())
return StatusWith<RecordId>(ErrorCodes::BadValue, "no ts field");
if (elem.type() != bsonTimestamp)
return StatusWith<RecordId>(ErrorCodes::BadValue, "ts must be a Timestamp");
return keyForOptime(elem.timestamp());
}
示例6: Status
StatusWith<ShardingMetadata> ShardingMetadata::readFromMetadata(const BSONObj& metadataObj) {
BSONElement smElem;
auto smExtractStatus =
bsonExtractTypedField(metadataObj, kGLEStatsFieldName, mongol::Object, &smElem);
if (!smExtractStatus.isOK()) {
return smExtractStatus;
}
if (smElem.embeddedObject().nFields() != 2) {
return Status(ErrorCodes::InvalidOptions,
str::stream() << "The $gleStats object can only have 2 fields, but got "
<< smElem.embeddedObject().toString());
}
repl::OpTime opTime;
const BSONElement opTimeElement = smElem.embeddedObject()[kGLEStatsLastOpTimeFieldName];
if (opTimeElement.eoo()) {
return Status(ErrorCodes::NoSuchKey, "lastOpTime field missing");
} else if (opTimeElement.type() == bsonTimestamp) {
opTime = repl::OpTime(opTimeElement.timestamp(), repl::OpTime::kUninitializedTerm);
} else if (opTimeElement.type() == Date) {
opTime = repl::OpTime(Timestamp(opTimeElement.date()), repl::OpTime::kUninitializedTerm);
} else if (opTimeElement.type() == Object) {
Status status =
bsonExtractOpTimeField(smElem.embeddedObject(), kGLEStatsLastOpTimeFieldName, &opTime);
if (!status.isOK()) {
return status;
}
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kGLEStatsLastOpTimeFieldName
<< "\" field in response to replSetHeartbeat "
"command to have type Date or Timestamp, but found type "
<< typeName(opTimeElement.type()));
}
BSONElement lastElectionIdElem;
auto lastElectionIdExtractStatus = bsonExtractTypedField(
smElem.embeddedObject(), kGLEStatsElectionIdFieldName, mongol::jstOID, &lastElectionIdElem);
if (!lastElectionIdExtractStatus.isOK()) {
return lastElectionIdExtractStatus;
}
return ShardingMetadata(opTime, lastElectionIdElem.OID());
}
示例7: it
StatusWith<ChunkVersion> ChunkVersion::parseFromBSONWithFieldForCommands(const BSONObj& obj,
StringData field) {
BSONElement versionElem;
Status status = bsonExtractField(obj, field, &versionElem);
if (!status.isOK())
return status;
if (versionElem.type() != Array) {
return {ErrorCodes::TypeMismatch,
str::stream() << "Invalid type " << versionElem.type()
<< " for shardVersion element. Expected an array"};
}
BSONObjIterator it(versionElem.Obj());
if (!it.more())
return {ErrorCodes::BadValue, "Unexpected empty version"};
ChunkVersion version;
// Expect the timestamp
{
BSONElement tsPart = it.next();
if (tsPart.type() != bsonTimestamp)
return {ErrorCodes::TypeMismatch,
str::stream() << "Invalid type " << tsPart.type()
<< " for version timestamp part."};
version._combined = tsPart.timestamp().asULL();
}
// Expect the epoch OID
{
BSONElement epochPart = it.next();
if (epochPart.type() != jstOID)
return {ErrorCodes::TypeMismatch,
str::stream() << "Invalid type " << epochPart.type()
<< " for version epoch part."};
version._epoch = epochPart.OID();
}
return version;
}
示例8: extract
FieldParser::FieldState FieldParser::extract(BSONElement elem,
const BSONField<Timestamp>& field,
Timestamp* out,
string* errMsg) {
if (elem.eoo()) {
if (field.hasDefault()) {
*out = field.getDefault();
return FIELD_DEFAULT;
} else {
return FIELD_NONE;
}
}
if (elem.type() == bsonTimestamp) {
*out = elem.timestamp();
return FIELD_SET;
}
_genFieldErrMsg(elem, field, "timestamp", errMsg);
return FIELD_INVALID;
}
示例9: runQuery
//.........这里部分代码省略.........
uassertStatusOK(serveReadsStatus);
// Run the query.
// bb is used to hold query results
// this buffer should contain either requested documents per query or
// explain information, but not both
BufBuilder bb(32768);
bb.skip(sizeof(QueryResult::Value));
// How many results have we obtained from the executor?
int numResults = 0;
// If we're replaying the oplog, we save the last time that we read.
Timestamp slaveReadTill;
BSONObj obj;
PlanExecutor::ExecState state;
// uint64_t numMisplacedDocs = 0;
// Get summary info about which plan the executor is using.
curop.debug().planSummary = Explain::getPlanSummary(exec.get());
while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
// Add result to output buffer.
bb.appendBuf((void*)obj.objdata(), obj.objsize());
// Count the result.
++numResults;
// Possibly note slave's position in the oplog.
if (pq.isOplogReplay()) {
BSONElement e = obj["ts"];
if (Date == e.type() || bsonTimestamp == e.type()) {
slaveReadTill = e.timestamp();
}
}
if (enoughForFirstBatch(pq, numResults, bb.len())) {
LOG(5) << "Enough for first batch, wantMore=" << pq.wantMore()
<< " numToReturn=" << pq.getNumToReturn()
<< " numResults=" << numResults
<< endl;
break;
}
}
// If we cache the executor later, we want to deregister it as it receives notifications
// anyway by virtue of being cached.
//
// If we don't cache the executor later, we are deleting it, so it must be deregistered.
//
// So, no matter what, deregister the executor.
exec->deregisterExec();
// Caller expects exceptions thrown in certain cases.
if (PlanExecutor::FAILURE == state) {
scoped_ptr<PlanStageStats> stats(exec->getStats());
error() << "Plan executor error, stats: "
<< Explain::statsToBSON(*stats);
uasserted(17144, "Executor error: " + WorkingSetCommon::toStatusString(obj));
}
// TODO: Currently, chunk ranges are kept around until all ClientCursors created while the
// chunk belonged on this node are gone. Separating chunk lifetime management from
// ClientCursor should allow this check to go away.
if (!shardingState.getVersion(nss.ns()).isWriteCompatibleWith(shardingVersionAtStart)) {
示例10: getMore
//.........这里部分代码省略.........
}
if (cc->isAggCursor()) {
// Agg cursors handle their own locking internally.
ctx.reset(); // unlocks
}
// If we're replaying the oplog, we save the last time that we read.
Timestamp slaveReadTill;
// What number result are we starting at? Used to fill out the reply.
startingResult = cc->pos();
// What gives us results.
PlanExecutor* exec = cc->getExecutor();
const int queryOptions = cc->queryOptions();
// Get results out of the executor.
exec->restoreState(txn);
BSONObj obj;
PlanExecutor::ExecState state;
while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
// Add result to output buffer.
bb.appendBuf((void*)obj.objdata(), obj.objsize());
// Count the result.
++numResults;
// Possibly note slave's position in the oplog.
if (queryOptions & QueryOption_OplogReplay) {
BSONElement e = obj["ts"];
if (Date == e.type() || bsonTimestamp == e.type()) {
slaveReadTill = e.timestamp();
}
}
if (enoughForGetMore(ntoreturn, numResults, bb.len())) {
break;
}
}
if (PlanExecutor::DEAD == state || PlanExecutor::FAILURE == state) {
// Propagate this error to caller.
if (PlanExecutor::FAILURE == state) {
scoped_ptr<PlanStageStats> stats(exec->getStats());
error() << "Plan executor error, stats: "
<< Explain::statsToBSON(*stats);
uasserted(17406, "getMore executor error: " +
WorkingSetCommon::toStatusString(obj));
}
// In the old system tailable capped cursors would be killed off at the
// cursorid level. If a tailable capped cursor is nuked the cursorid
// would vanish.
//
// In the new system they die and are cleaned up later (or time out).
// So this is where we get to remove the cursorid.
if (0 == numResults) {
resultFlags = ResultFlag_CursorNotFound;
}
}
const bool shouldSaveCursor =
shouldSaveCursorGetMore(state, exec, isCursorTailable(cc));
示例11: dcmlNorm
void BSONComparatorInterfaceBase<T>::hashCombineBSONElement(
size_t& hash,
BSONElement elemToHash,
bool considerFieldName,
const StringData::ComparatorInterface* stringComparator) {
boost::hash_combine(hash, elemToHash.canonicalType());
const StringData fieldName = elemToHash.fieldNameStringData();
if (considerFieldName && !fieldName.empty()) {
SimpleStringDataComparator::kInstance.hash_combine(hash, fieldName);
}
switch (elemToHash.type()) {
// Order of types is the same as in compareElementValues().
case mongo::EOO:
case mongo::Undefined:
case mongo::jstNULL:
case mongo::MaxKey:
case mongo::MinKey:
// These are valueless types
break;
case mongo::Bool:
boost::hash_combine(hash, elemToHash.boolean());
break;
case mongo::bsonTimestamp:
boost::hash_combine(hash, elemToHash.timestamp().asULL());
break;
case mongo::Date:
boost::hash_combine(hash, elemToHash.date().asInt64());
break;
case mongo::NumberDecimal: {
const Decimal128 dcml = elemToHash.numberDecimal();
if (dcml.toAbs().isGreater(Decimal128(std::numeric_limits<double>::max(),
Decimal128::kRoundTo34Digits,
Decimal128::kRoundTowardZero)) &&
!dcml.isInfinite() && !dcml.isNaN()) {
// Normalize our decimal to force equivalent decimals
// in the same cohort to hash to the same value
Decimal128 dcmlNorm(dcml.normalize());
boost::hash_combine(hash, dcmlNorm.getValue().low64);
boost::hash_combine(hash, dcmlNorm.getValue().high64);
break;
}
// Else, fall through and convert the decimal to a double and hash.
// At this point the decimal fits into the range of doubles, is infinity, or is NaN,
// which doubles have a cheaper representation for.
}
case mongo::NumberDouble:
case mongo::NumberLong:
case mongo::NumberInt: {
// This converts all numbers to doubles, which ignores the low-order bits of
// NumberLongs > 2**53 and precise decimal numbers without double representations,
// but that is ok since the hash will still be the same for equal numbers and is
// still likely to be different for different numbers. (Note: this issue only
// applies for decimals when they are outside of the valid double range. See
// the above case.)
// SERVER-16851
const double dbl = elemToHash.numberDouble();
if (std::isnan(dbl)) {
boost::hash_combine(hash, std::numeric_limits<double>::quiet_NaN());
} else {
boost::hash_combine(hash, dbl);
}
break;
}
case mongo::jstOID:
elemToHash.__oid().hash_combine(hash);
break;
case mongo::String: {
if (stringComparator) {
stringComparator->hash_combine(hash, elemToHash.valueStringData());
} else {
SimpleStringDataComparator::kInstance.hash_combine(hash,
elemToHash.valueStringData());
}
break;
}
case mongo::Code:
case mongo::Symbol:
SimpleStringDataComparator::kInstance.hash_combine(hash, elemToHash.valueStringData());
break;
case mongo::Object:
case mongo::Array:
hashCombineBSONObj(hash,
elemToHash.embeddedObject(),
true, // considerFieldName
stringComparator);
break;
case mongo::DBRef:
case mongo::BinData:
//.........这里部分代码省略.........
示例12: initialize
Status ReplSetHeartbeatResponse::initialize(const BSONObj& doc, long long term) {
// Old versions set this even though they returned not "ok"
_mismatch = doc[kMismatchFieldName].trueValue();
if (_mismatch)
return Status(ErrorCodes::InconsistentReplicaSetNames, "replica set name doesn't match.");
// Old versions sometimes set the replica set name ("set") but ok:0
const BSONElement replSetNameElement = doc[kReplSetFieldName];
if (replSetNameElement.eoo()) {
_setName.clear();
} else if (replSetNameElement.type() != String) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kReplSetFieldName
<< "\" field in response to replSetHeartbeat to have "
"type String, but found "
<< typeName(replSetNameElement.type()));
} else {
_setName = replSetNameElement.String();
}
if (_setName.empty() && !doc[kOkFieldName].trueValue()) {
std::string errMsg = doc[kErrMsgFieldName].str();
BSONElement errCodeElem = doc[kErrorCodeFieldName];
if (errCodeElem.ok()) {
if (!errCodeElem.isNumber())
return Status(ErrorCodes::BadValue, "Error code is not a number!");
int errorCode = errCodeElem.numberInt();
return Status(ErrorCodes::Error(errorCode), errMsg);
}
return Status(ErrorCodes::UnknownError, errMsg);
}
const BSONElement hasDataElement = doc[kHasDataFieldName];
_hasDataSet = !hasDataElement.eoo();
_hasData = hasDataElement.trueValue();
const BSONElement electionTimeElement = doc[kElectionTimeFieldName];
if (electionTimeElement.eoo()) {
_electionTimeSet = false;
} else if (electionTimeElement.type() == bsonTimestamp) {
_electionTimeSet = true;
_electionTime = electionTimeElement.timestamp();
} else if (electionTimeElement.type() == Date) {
_electionTimeSet = true;
_electionTime = Timestamp(electionTimeElement.date());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kElectionTimeFieldName
<< "\" field in response to replSetHeartbeat "
"command to have type Date or Timestamp, but found type "
<< typeName(electionTimeElement.type()));
}
const BSONElement timeElement = doc[kTimeFieldName];
if (timeElement.eoo()) {
_timeSet = false;
} else if (timeElement.isNumber()) {
_timeSet = true;
_time = Seconds(timeElement.numberLong());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kTimeFieldName
<< "\" field in response to replSetHeartbeat "
"command to have a numeric type, but found type "
<< typeName(timeElement.type()));
}
_isReplSet = doc[kIsReplSetFieldName].trueValue();
Status termStatus = bsonExtractIntegerField(doc, kTermFieldName, &_term);
if (!termStatus.isOK() && termStatus != ErrorCodes::NoSuchKey) {
return termStatus;
}
// In order to support both the 3.0(V0) and 3.2(V1) heartbeats we must parse the OpTime
// field based on its type. If it is a Date, we parse it as the timestamp and use
// initialize's term argument to complete the OpTime type. If it is an Object, then it's
// V1 and we construct an OpTime out of its nested fields.
const BSONElement opTimeElement = doc[kOpTimeFieldName];
if (opTimeElement.eoo()) {
_opTimeSet = false;
} else if (opTimeElement.type() == bsonTimestamp) {
_opTimeSet = true;
_opTime = OpTime(opTimeElement.timestamp(), term);
} else if (opTimeElement.type() == Date) {
_opTimeSet = true;
_opTime = OpTime(Timestamp(opTimeElement.date()), term);
} else if (opTimeElement.type() == Object) {
Status status = bsonExtractOpTimeField(doc, kOpTimeFieldName, &_opTime);
_opTimeSet = true;
// since a v1 OpTime was in the response, the member must be part of a replset
_isReplSet = true;
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected \"" << kOpTimeFieldName
<< "\" field in response to replSetHeartbeat "
"command to have type Date or Timestamp, but found type "
<< typeName(opTimeElement.type()));
//.........这里部分代码省略.........
示例13: parseBSON
bool BatchedCommandResponse::parseBSON(const BSONObj& source, string* errMsg) {
clear();
std::string dummy;
if (!errMsg)
errMsg = &dummy;
FieldParser::FieldState fieldState;
fieldState = FieldParser::extractNumber(source, ok, &_ok, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_isOkSet = fieldState == FieldParser::FIELD_SET;
fieldState = FieldParser::extract(source, errCode, &_errCode, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_isErrCodeSet = fieldState == FieldParser::FIELD_SET;
fieldState = FieldParser::extract(source, errMessage, &_errMessage, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_isErrMessageSet = fieldState == FieldParser::FIELD_SET;
// We're using appendNumber on generation so we'll try a smaller type
// (int) first and then fall back to the original type (long long).
BSONField<int> fieldN(n());
int tempN;
fieldState = FieldParser::extract(source, fieldN, &tempN, errMsg);
if (fieldState == FieldParser::FIELD_INVALID) {
// try falling back to a larger type
fieldState = FieldParser::extract(source, n, &_n, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_isNSet = fieldState == FieldParser::FIELD_SET;
} else if (fieldState == FieldParser::FIELD_SET) {
_isNSet = true;
_n = tempN;
}
// We're using appendNumber on generation so we'll try a smaller type
// (int) first and then fall back to the original type (long long).
BSONField<int> fieldNModified(nModified());
int intNModified;
fieldState = FieldParser::extract(source, fieldNModified, &intNModified, errMsg);
if (fieldState == FieldParser::FIELD_INVALID) {
// try falling back to a larger type
fieldState = FieldParser::extract(source, nModified, &_nModified, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_isNModifiedSet = fieldState == FieldParser::FIELD_SET;
} else if (fieldState == FieldParser::FIELD_SET) {
_isNModifiedSet = true;
_nModified = intNModified;
}
std::vector<BatchedUpsertDetail*>* tempUpsertDetails = NULL;
fieldState = FieldParser::extract(source, upsertDetails, &tempUpsertDetails, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_upsertDetails.reset(tempUpsertDetails);
const BSONElement opTimeElement = source["opTime"];
_isLastOpSet = true;
if (opTimeElement.eoo()) {
_isLastOpSet = false;
} else if (opTimeElement.type() == bsonTimestamp) {
_lastOp = repl::OpTime(opTimeElement.timestamp(), repl::OpTime::kUninitializedTerm);
} else if (opTimeElement.type() == Date) {
_lastOp = repl::OpTime(Timestamp(opTimeElement.date()), repl::OpTime::kUninitializedTerm);
} else if (opTimeElement.type() == Object) {
Status status = bsonExtractOpTimeField(source, "opTime", &_lastOp);
if (!status.isOK()) {
return false;
}
} else {
return false;
}
fieldState = FieldParser::extract(source, electionId, &_electionId, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_isElectionIdSet = fieldState == FieldParser::FIELD_SET;
std::vector<WriteErrorDetail*>* tempErrDetails = NULL;
fieldState = FieldParser::extract(source, writeErrors, &tempErrDetails, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_writeErrorDetails.reset(tempErrDetails);
WCErrorDetail* wcError = NULL;
fieldState = FieldParser::extract(source, writeConcernError, &wcError, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_wcErrDetails.reset(wcError);
return true;
}
示例14: runQuery
//.........这里部分代码省略.........
// How many results have we obtained from the executor?
int numResults = 0;
// If we're replaying the oplog, we save the last time that we read.
Timestamp slaveReadTill;
BSONObj obj;
PlanExecutor::ExecState state;
// Get summary info about which plan the executor is using.
{
stdx::lock_guard<Client> lk(*txn->getClient());
curop.setPlanSummary_inlock(Explain::getPlanSummary(exec.get()));
}
while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) {
// If we can't fit this result inside the current batch, then we stash it for later.
if (!FindCommon::haveSpaceForNext(obj, numResults, bb.len())) {
exec->enqueue(obj);
break;
}
// Add result to output buffer.
bb.appendBuf((void*)obj.objdata(), obj.objsize());
// Count the result.
++numResults;
// Possibly note slave's position in the oplog.
if (pq.isOplogReplay()) {
BSONElement e = obj["ts"];
if (Date == e.type() || bsonTimestamp == e.type()) {
slaveReadTill = e.timestamp();
}
}
if (FindCommon::enoughForFirstBatch(pq, numResults)) {
LOG(5) << "Enough for first batch, wantMore=" << pq.wantMore()
<< " ntoreturn=" << pq.getNToReturn().value_or(0) << " numResults=" << numResults
<< endl;
break;
}
}
// If we cache the executor later, we want to deregister it as it receives notifications
// anyway by virtue of being cached.
//
// If we don't cache the executor later, we are deleting it, so it must be deregistered.
//
// So, no matter what, deregister the executor.
exec->deregisterExec();
// Caller expects exceptions thrown in certain cases.
if (PlanExecutor::FAILURE == state || PlanExecutor::DEAD == state) {
error() << "Plan executor error during find: " << PlanExecutor::statestr(state)
<< ", stats: " << Explain::getWinningPlanStats(exec.get());
uasserted(17144, "Executor error: " + WorkingSetCommon::toStatusString(obj));
}
// Before saving the cursor, ensure that whatever plan we established happened with the expected
// collection version
auto css = CollectionShardingState::get(txn, nss);
css->checkShardVersionOrThrow(txn);
// Fill out curop based on query results. If we have a cursorid, we will fill out curop with
示例15: compareElements
int BSONElement::compareElements(const BSONElement& l,
const BSONElement& r,
ComparisonRulesSet rules,
const StringData::ComparatorInterface* comparator) {
switch (l.type()) {
case BSONType::EOO:
case BSONType::Undefined: // EOO and Undefined are same canonicalType
case BSONType::jstNULL:
case BSONType::MaxKey:
case BSONType::MinKey: {
auto f = l.canonicalType() - r.canonicalType();
if (f < 0)
return -1;
return f == 0 ? 0 : 1;
}
case BSONType::Bool:
return *l.value() - *r.value();
case BSONType::bsonTimestamp:
// unsigned compare for timestamps - note they are not really dates but (ordinal +
// time_t)
if (l.timestamp() < r.timestamp())
return -1;
return l.timestamp() == r.timestamp() ? 0 : 1;
case BSONType::Date:
// Signed comparisons for Dates.
{
const Date_t a = l.Date();
const Date_t b = r.Date();
if (a < b)
return -1;
return a == b ? 0 : 1;
}
case BSONType::NumberInt: {
// All types can precisely represent all NumberInts, so it is safe to simply convert to
// whatever rhs's type is.
switch (r.type()) {
case NumberInt:
return compareInts(l._numberInt(), r._numberInt());
case NumberLong:
return compareLongs(l._numberInt(), r._numberLong());
case NumberDouble:
return compareDoubles(l._numberInt(), r._numberDouble());
case NumberDecimal:
return compareIntToDecimal(l._numberInt(), r._numberDecimal());
default:
MONGO_UNREACHABLE;
}
}
case BSONType::NumberLong: {
switch (r.type()) {
case NumberLong:
return compareLongs(l._numberLong(), r._numberLong());
case NumberInt:
return compareLongs(l._numberLong(), r._numberInt());
case NumberDouble:
return compareLongToDouble(l._numberLong(), r._numberDouble());
case NumberDecimal:
return compareLongToDecimal(l._numberLong(), r._numberDecimal());
default:
MONGO_UNREACHABLE;
}
}
case BSONType::NumberDouble: {
switch (r.type()) {
case NumberDouble:
return compareDoubles(l._numberDouble(), r._numberDouble());
case NumberInt:
return compareDoubles(l._numberDouble(), r._numberInt());
case NumberLong:
return compareDoubleToLong(l._numberDouble(), r._numberLong());
case NumberDecimal:
return compareDoubleToDecimal(l._numberDouble(), r._numberDecimal());
default:
MONGO_UNREACHABLE;
}
}
case BSONType::NumberDecimal: {
switch (r.type()) {
case NumberDecimal:
return compareDecimals(l._numberDecimal(), r._numberDecimal());
case NumberInt:
return compareDecimalToInt(l._numberDecimal(), r._numberInt());
case NumberLong:
return compareDecimalToLong(l._numberDecimal(), r._numberLong());
case NumberDouble:
return compareDecimalToDouble(l._numberDecimal(), r._numberDouble());
default:
MONGO_UNREACHABLE;
}
}
case BSONType::jstOID:
return memcmp(l.value(), r.value(), OID::kOIDSize);
case BSONType::Code:
return compareElementStringValues(l, r);
case BSONType::Symbol:
//.........这里部分代码省略.........