本文整理汇总了C++中BSONElement::safeNumberLong方法的典型用法代码示例。如果您正苦于以下问题:C++ BSONElement::safeNumberLong方法的具体用法?C++ BSONElement::safeNumberLong怎么用?C++ BSONElement::safeNumberLong使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BSONElement
的用法示例。
在下文中一共展示了BSONElement::safeNumberLong方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: getIdentSize
int64_t WiredTigerUtil::getIdentSize(WT_SESSION* s,
const std::string& uri ) {
BSONObjBuilder b;
Status status = WiredTigerUtil::exportTableToBSON(s,
"statistics:" + uri,
"statistics=(fast)",
&b);
if ( !status.isOK() ) {
if ( status.code() == ErrorCodes::CursorNotFound ) {
// ident gone, so its 0
return 0;
}
uassertStatusOK( status );
}
BSONObj obj = b.obj();
BSONObj sub = obj["block-manager"].Obj();
BSONElement e = sub["file size in bytes"];
invariant( e.type() );
if ( e.isNumber() )
return e.safeNumberLong();
return strtoull( e.valuestrsafe(), NULL, 10 );
}
示例2: loadLastAppliedHash
void BackgroundSync::loadLastAppliedHash(OperationContext* txn) {
BSONObj oplogEntry;
try {
if (!Helpers::getLast(txn, rsoplog, oplogEntry)) {
// This can happen when we are to do an initial sync. lastHash will be set
// after the initial sync is complete.
_lastAppliedHash = 0;
return;
}
}
catch (const DBException& ex) {
severe() << "Problem reading " << rsoplog << ": " << ex.toStatus();
fassertFailed(18904);
}
BSONElement hashElement = oplogEntry[hashFieldName];
if (hashElement.eoo()) {
severe() << "Most recent entry in " << rsoplog << " missing \"" << hashFieldName <<
"\" field";
fassertFailed(18902);
}
if (hashElement.type() != NumberLong) {
severe() << "Expected type of \"" << hashFieldName << "\" in most recent " <<
rsoplog << " entry to have type NumberLong, but found " <<
typeName(hashElement.type());
fassertFailed(18903);
}
_lastAppliedHash = hashElement.safeNumberLong();
}
示例3: _readLastAppliedHash
long long BackgroundSync::_readLastAppliedHash(OperationContext* txn) {
BSONObj oplogEntry;
try {
MONGO_WRITE_CONFLICT_RETRY_LOOP_BEGIN {
ScopedTransaction transaction(txn, MODE_IX);
Lock::DBLock lk(txn->lockState(), "local", MODE_X);
bool success = Helpers::getLast(txn, rsOplogName.c_str(), oplogEntry);
if (!success) {
// This can happen when we are to do an initial sync. lastHash will be set
// after the initial sync is complete.
return 0;
}
}
MONGO_WRITE_CONFLICT_RETRY_LOOP_END(txn, "readLastAppliedHash", rsOplogName);
} catch (const DBException& ex) {
severe() << "Problem reading " << rsOplogName << ": " << ex.toStatus();
fassertFailed(18904);
}
BSONElement hashElement = oplogEntry[hashFieldName];
if (hashElement.eoo()) {
severe() << "Most recent entry in " << rsOplogName << " missing \"" << hashFieldName
<< "\" field";
fassertFailed(18902);
}
if (hashElement.type() != NumberLong) {
severe() << "Expected type of \"" << hashFieldName << "\" in most recent " << rsOplogName
<< " entry to have type NumberLong, but found " << typeName(hashElement.type());
fassertFailed(18903);
}
return hashElement.safeNumberLong();
}
示例4: _readLastAppliedHash
long long BackgroundSync::_readLastAppliedHash(OperationContext* txn) {
BSONObj oplogEntry;
try {
// Uses WuoW because there is no way to demarcate a read transaction boundary.
Lock::DBLock lk(txn->lockState(), "local", MODE_X);
WriteUnitOfWork uow(txn);
bool success = Helpers::getLast(txn, rsoplog, oplogEntry);
uow.commit();
if (!success) {
// This can happen when we are to do an initial sync. lastHash will be set
// after the initial sync is complete.
return 0;
}
}
catch (const DBException& ex) {
severe() << "Problem reading " << rsoplog << ": " << ex.toStatus();
fassertFailed(18904);
}
BSONElement hashElement = oplogEntry[hashFieldName];
if (hashElement.eoo()) {
severe() << "Most recent entry in " << rsoplog << " missing \"" << hashFieldName <<
"\" field";
fassertFailed(18902);
}
if (hashElement.type() != NumberLong) {
severe() << "Expected type of \"" << hashFieldName << "\" in most recent " <<
rsoplog << " entry to have type NumberLong, but found " <<
typeName(hashElement.type());
fassertFailed(18903);
}
return hashElement.safeNumberLong();
}
示例5: init
void ParsedQuery::init( const BSONObj& q ) {
_reset();
uassert( 10105 , "bad skip value in query", _ntoskip >= 0);
if ( _ntoreturn < 0 ) {
/* _ntoreturn greater than zero is simply a hint on how many objects to send back per
"cursor batch".
A negative number indicates a hard limit.
*/
_wantMore = false;
_ntoreturn = -_ntoreturn;
}
BSONElement e = q["query"];
if ( ! e.isABSONObj() )
e = q["$query"];
if ( e.isABSONObj() ) {
_filter = e.embeddedObject();
_initTop( q );
}
else {
_filter = q;
}
_filter = _filter.getOwned();
//
// Parse options that are valid for both queries and commands
//
// $readPreference
_hasReadPref = q.hasField(Query::ReadPrefField.name());
// $maxTimeMS
BSONElement maxTimeMSElt = q.getField("$maxTimeMS");
if (!maxTimeMSElt.eoo()) {
uassert(16987,
mongoutils::str::stream() <<
"$maxTimeMS must be a number type, instead found type: " <<
maxTimeMSElt.type(),
maxTimeMSElt.isNumber());
}
// If $maxTimeMS was not specified, _maxTimeMS is set to 0 (special value for "allow to
// run indefinitely").
long long maxTimeMSLongLong = maxTimeMSElt.safeNumberLong();
uassert(16988,
"$maxTimeMS out of range [0,2147483647]",
maxTimeMSLongLong >= 0 && maxTimeMSLongLong <= INT_MAX);
_maxTimeMS = static_cast<int>(maxTimeMSLongLong);
}
示例6: isValidSortOrder
// static
bool LiteParsedQuery::isValidSortOrder(const BSONObj& sortObj) {
BSONObjIterator i(sortObj);
while (i.more()) {
BSONElement e = i.next();
if (isTextMeta(e)) {
continue;
}
long long n = e.safeNumberLong();
if (!(e.isNumber() && (n == -1LL || n == 1LL))) {
return false;
}
}
return true;
}
示例7: getSortPattern
// static
BSONObj QueryPlannerAnalysis::getSortPattern(const BSONObj& indexKeyPattern) {
BSONObjBuilder sortBob;
BSONObjIterator kpIt(indexKeyPattern);
while (kpIt.more()) {
BSONElement elt = kpIt.next();
if (elt.type() == mongo::String) {
break;
}
long long val = elt.safeNumberLong();
int sortOrder = val >= 0 ? 1 : -1;
sortBob.append(elt.fieldName(), sortOrder);
}
return sortBob.obj();
}
示例8: normalizeSortOrder
// static
BSONObj LiteParsedQuery::normalizeSortOrder(const BSONObj& sortObj) {
BSONObjBuilder b;
BSONObjIterator i(sortObj);
while (i.more()) {
BSONElement e = i.next();
if (isTextScoreMeta(e)) {
b.append(e);
continue;
}
long long n = e.safeNumberLong();
int sortOrder = n >= 0 ? 1 : -1;
b.append(e.fieldName(), sortOrder);
}
return b.obj();
}
示例9: isValidSortOrder
// static
bool LiteParsedQuery::isValidSortOrder(const BSONObj& sortObj) {
BSONObjIterator i(sortObj);
while (i.more()) {
BSONElement e = i.next();
// fieldNameSize() includes NULL terminator. For empty field name,
// we should be checking for 1 instead of 0.
if (1 == e.fieldNameSize()) {
return false;
}
if (isTextScoreMeta(e)) {
continue;
}
long long n = e.safeNumberLong();
if (!(e.isNumber() && (n == -1LL || n == 1LL))) {
return false;
}
}
return true;
}
示例10: recursiveHash
void BSONElementHasher::recursiveHash( Hasher* h ,
const BSONElement& e ,
bool includeFieldName ) {
int canonicalType = e.canonicalType();
h->addData( &canonicalType , sizeof( canonicalType ) );
if ( includeFieldName ){
h->addData( e.fieldName() , e.fieldNameSize() );
}
if ( !e.mayEncapsulate() ){
//if there are no embedded objects (subobjects or arrays),
//compute the hash, squashing numeric types to 64-bit ints
if ( e.isNumber() ){
long long int i = e.safeNumberLong(); //well-defined for troublesome doubles
h->addData( &i , sizeof( i ) );
}
else {
h->addData( e.value() , e.valuesize() );
}
}
else {
//else identify the subobject.
//hash any preceding stuff (in the case of codeWscope)
//then each sub-element
//then finish with the EOO element.
BSONObj b;
if ( e.type() == CodeWScope ) {
h->addData( e.codeWScopeCode() , e.codeWScopeCodeLen() );
b = e.codeWScopeObject();
}
else {
b = e.embeddedObject();
}
BSONObjIterator i(b);
while( i.moreWithEOO() ) {
BSONElement el = i.next();
recursiveHash( h , el , true );
}
}
}
示例11: run
virtual bool run(const string &db, BSONObj &cmdObj, int options, string &errmsg, BSONObjBuilder &result, bool fromRepl) {
BSONElement e = cmdObj.firstElement();
long long bps;
if (e.type() == String) {
Status status = BytesQuantity<long long>::fromString(e.Stringdata(), bps);
if (!status.isOK()) {
stringstream ss;
ss << "error parsing number " << e.Stringdata() << ": " << status.codeString() << " " << status.reason();
errmsg = ss.str();
return false;
}
}
else {
if (!e.isNumber()) {
errmsg = "backupThrottle argument must be a number";
return false;
}
bps = e.safeNumberLong();
}
return Manager::throttle(bps, errmsg, result);
}
示例12: bsonExtractIntegerField
Status bsonExtractIntegerField(const BSONObj& object,
const StringData& fieldName,
long long* out) {
BSONElement value;
Status status = bsonExtractField(object, fieldName, &value);
if (!status.isOK())
return status;
if (!value.isNumber()) {
return Status(ErrorCodes::TypeMismatch, mongoutils::str::stream() <<
"Expected field \"" << fieldName <<
"\" to have numeric type, but found " << typeName(value.type()));
}
long long result = value.safeNumberLong();
if (result != value.numberDouble()) {
return Status(ErrorCodes::BadValue, mongoutils::str::stream() <<
"Expected field \"" << fieldName << "\" to have a value "
"exactly representable as a 64-bit integer, but found " <<
value);
}
*out = result;
return Status::OK();
}
示例13: floor
// static
StatusWith<int> LiteParsedQuery::parseMaxTimeMS(const BSONElement& maxTimeMSElt) {
if (!maxTimeMSElt.eoo() && !maxTimeMSElt.isNumber()) {
return StatusWith<int>(ErrorCodes::BadValue,
(StringBuilder()
<< maxTimeMSElt.fieldNameStringData()
<< " must be a number").str());
}
long long maxTimeMSLongLong = maxTimeMSElt.safeNumberLong(); // returns 0 on EOO
if (maxTimeMSLongLong < 0 || maxTimeMSLongLong > INT_MAX) {
return StatusWith<int>(ErrorCodes::BadValue,
(StringBuilder()
<< maxTimeMSElt.fieldNameStringData()
<< " is out of range").str());
}
double maxTimeMSDouble = maxTimeMSElt.numberDouble();
if (maxTimeMSElt.type() == mongo::NumberDouble
&& floor(maxTimeMSDouble) != maxTimeMSDouble) {
return StatusWith<int>(ErrorCodes::BadValue,
(StringBuilder()
<< maxTimeMSElt.fieldNameStringData()
<< " has non-integral value").str());
}
return StatusWith<int>(static_cast<int>(maxTimeMSLongLong));
}
示例14: init
Status LiteParsedQuery::init(const string& ns, int ntoskip, int ntoreturn, int queryOptions,
const BSONObj& queryObj, bool fromQueryMessage) {
_ns = ns;
_ntoskip = ntoskip;
_ntoreturn = ntoreturn;
_options = queryOptions;
// TODO: If pq.hasOption(QueryOption_CursorTailable) make sure it's a capped collection and
// make sure the order(??) is $natural: 1.
if (_ntoskip < 0) {
return Status(ErrorCodes::BadValue, "bad skip value in query");
}
if (_ntoreturn < 0) {
// _ntoreturn greater than zero is simply a hint on how many objects to send back per
// "cursor batch". A negative number indicates a hard limit.
_wantMore = false;
_ntoreturn = -_ntoreturn;
}
if (fromQueryMessage) {
BSONElement queryField = queryObj["query"];
if (!queryField.isABSONObj()) { queryField = queryObj["$query"]; }
if (queryField.isABSONObj()) {
_filter = queryField.embeddedObject().getOwned();
Status status = initFullQuery(queryObj);
if (!status.isOK()) { return status; }
}
else {
// TODO: Does this ever happen?
_filter = queryObj.getOwned();
}
}
else {
// This is the debugging code path.
_filter = queryObj.getOwned();
}
//
// Parse options that are valid for both queries and commands
//
// $readPreference
_hasReadPref = queryObj.hasField("$readPreference");
// $maxTimeMS
BSONElement maxTimeMSElt = queryObj.getField("$maxTimeMS");
if (!maxTimeMSElt.eoo() && !maxTimeMSElt.isNumber()) {
return Status(ErrorCodes::BadValue, "$maxTimeMS must be a number");
}
// If $maxTimeMS was not specified, _maxTimeMS is set to 0 (special value for "allow to
// run indefinitely").
long long maxTimeMSLongLong = maxTimeMSElt.safeNumberLong();
if (maxTimeMSLongLong < 0 || maxTimeMSLongLong > INT_MAX) {
return Status(ErrorCodes::BadValue, "$maxTimeMS is out of range");
}
_maxTimeMS = static_cast<int>(maxTimeMSLongLong);
return Status::OK();
}
示例15: _collModInternal
//.........这里部分代码省略.........
BSONArrayBuilder pipeline;
for (auto& item : view->pipeline()) {
pipeline.append(item);
}
auto errorStatus =
catalog->modifyView(opCtx, nss, view->viewOn(), BSONArray(pipeline.obj()));
if (!errorStatus.isOK()) {
return errorStatus;
}
wunit.commit();
return Status::OK();
}
// In order to facilitate the replication rollback process, which makes a best effort attempt to
// "undo" a set of oplog operations, we store a snapshot of the old collection options to
// provide to the OpObserver. TTL index updates aren't a part of collection options so we
// save the relevant TTL index data in a separate object.
CollectionOptions oldCollOptions = coll->getCatalogEntry()->getCollectionOptions(opCtx);
boost::optional<TTLCollModInfo> ttlInfo;
// Handle collMod operation type appropriately.
// TTLIndex
if (!cmr.indexExpireAfterSeconds.eoo()) {
BSONElement& newExpireSecs = cmr.indexExpireAfterSeconds;
BSONElement oldExpireSecs = cmr.idx->infoObj().getField("expireAfterSeconds");
if (SimpleBSONElementComparator::kInstance.evaluate(oldExpireSecs != newExpireSecs)) {
result->appendAs(oldExpireSecs, "expireAfterSeconds_old");
// Change the value of "expireAfterSeconds" on disk.
coll->getCatalogEntry()->updateTTLSetting(
opCtx, cmr.idx->indexName(), newExpireSecs.safeNumberLong());
// Notify the index catalog that the definition of this index changed.
cmr.idx = coll->getIndexCatalog()->refreshEntry(opCtx, cmr.idx);
result->appendAs(newExpireSecs, "expireAfterSeconds_new");
opCtx->recoveryUnit()->onRollback([ opCtx, idx = cmr.idx, coll ]() {
coll->getIndexCatalog()->refreshEntry(opCtx, idx);
});
}
// Save previous TTL index expiration.
ttlInfo = TTLCollModInfo{Seconds(newExpireSecs.safeNumberLong()),
Seconds(oldExpireSecs.safeNumberLong()),
cmr.idx->indexName()};
}
// The Validator, ValidationAction and ValidationLevel are already parsed and must be OK.
if (!cmr.collValidator.eoo())
invariant(coll->setValidator(opCtx, cmr.collValidator.Obj()));
if (!cmr.collValidationAction.empty())
invariant(coll->setValidationAction(opCtx, cmr.collValidationAction));
if (!cmr.collValidationLevel.empty())
invariant(coll->setValidationLevel(opCtx, cmr.collValidationLevel));
// UsePowerof2Sizes
if (!cmr.usePowerOf2Sizes.eoo())
setCollectionOptionFlag(opCtx, coll, cmr.usePowerOf2Sizes, result);
// NoPadding
if (!cmr.noPadding.eoo())
setCollectionOptionFlag(opCtx, coll, cmr.noPadding, result);
// Upgrade unique indexes
if (upgradeUniqueIndexes) {
// A cmdObj with an empty collMod, i.e. nFields = 1, implies that it is a Unique Index
// upgrade collMod.
invariant(cmdObj.nFields() == 1);
std::vector<std::string> indexNames;
coll->getCatalogEntry()->getAllUniqueIndexes(opCtx, &indexNames);
for (size_t i = 0; i < indexNames.size(); i++) {
const IndexDescriptor* desc =
coll->getIndexCatalog()->findIndexByName(opCtx, indexNames[i]);
invariant(desc);
// Update index metadata in storage engine.
coll->getCatalogEntry()->updateIndexMetadata(opCtx, desc);
// Refresh the in-memory instance of the index.
desc = coll->getIndexCatalog()->refreshEntry(opCtx, desc);
opCtx->recoveryUnit()->onRollback(
[opCtx, desc, coll]() { coll->getIndexCatalog()->refreshEntry(opCtx, desc); });
}
}
// Only observe non-view collMods, as view operations are observed as operations on the
// system.views collection.
getGlobalServiceContext()->getOpObserver()->onCollMod(
opCtx, nss, coll->uuid(), oplogEntryBuilder.obj(), oldCollOptions, ttlInfo);
wunit.commit();
return Status::OK();
}