本文整理汇总了C++中BSONElement::eoo方法的典型用法代码示例。如果您正苦于以下问题:C++ BSONElement::eoo方法的具体用法?C++ BSONElement::eoo怎么用?C++ BSONElement::eoo使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BSONElement
的用法示例。
在下文中一共展示了BSONElement::eoo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: _runLoop
INT32 _fmpController::_runLoop()
{
INT32 rc = SDB_OK ;
BSONObj obj ;
BSONElement ele ;
while ( TRUE )
{
INT32 step = FMP_CONTROL_STEP_INVALID ;
rc = _readMsg( obj ) ;
if ( SDB_OK != rc )
{
PD_LOG( PDERROR, "failed to read msg:%d",rc ) ;
goto error ;
}
ele = obj.getField( FMP_CONTROL_FIELD ) ;
if ( ele.eoo() )
{
step = FMP_CONTROL_STEP_DOWNLOAD ;
}
else if ( NumberInt != ele.type() )
{
PD_LOG( PDERROR, "failed to find control filed:%s",
obj.toString().c_str() ) ;
rc = SDB_SYS ;
goto error ;
}
else
{
step = ele.Int() ;
}
if ( FMP_CONTROL_STEP_QUIT == step )
{
_clear() ;
rc = _writeMsg( OK_RES ) ;
if ( SDB_OK != rc )
{
PD_LOG( PDERROR, "failed to write res of reset:%d", rc ) ;
goto error ;
}
break ;
}
else if ( FMP_CONTROL_STEP_RESET == step )
{
_clear() ;
rc = _writeMsg( OK_RES ) ;
if ( SDB_OK != rc )
{
PD_LOG( PDERROR, "failed to write res of reset:%d", rc ) ;
goto error ;
}
continue ;
}
else
{
}
if ( !FMP_VALID_STEP(step) )
{
PD_LOG( PDERROR, "invalid step number[%d], now step[%d]",
ele.Int(), _step ) ;
rc = SDB_SYS ;
goto error ;
}
rc = _handleOneLoop( obj, step ) ;
if ( SDB_OK != rc )
{
PD_LOG( PDERROR, "failed to handle one loop:%d", rc) ;
_clear() ;
}
FMP_STEP_AUTO_CHANGE( step ) ;
}
done:
return rc ;
error:
goto done ;
}
示例2: jsonString
string BSONElement::jsonString( JsonStringFormat format, bool includeFieldNames, int pretty ) const {
BSONType t = type();
if ( t == Undefined )
return "";
stringstream s;
if ( includeFieldNames )
s << '"' << escape( fieldName() ) << "\" : ";
switch ( type() ) {
case mongo::String:
case Symbol:
s << '"' << escape( valuestr() ) << '"';
break;
case NumberLong:
s << _numberLong();
break;
case NumberInt:
case NumberDouble:
if ( number() >= -numeric_limits< double >::max() &&
number() <= numeric_limits< double >::max() ) {
s.precision( 16 );
s << number();
} else {
stringstream ss;
ss << "Number " << number() << " cannot be represented in JSON";
string message = ss.str();
massert( 10311 , message.c_str(), false );
}
break;
case mongo::Bool:
s << ( boolean() ? "true" : "false" );
break;
case jstNULL:
s << "null";
break;
case Object:
s << embeddedObject().jsonString( format, pretty );
break;
case mongo::Array: {
if ( embeddedObject().isEmpty() ) {
s << "[]";
break;
}
s << "[ ";
BSONObjIterator i( embeddedObject() );
BSONElement e = i.next();
if ( !e.eoo() )
while ( 1 ) {
if( pretty ) {
s << '\n';
for( int x = 0; x < pretty; x++ )
s << " ";
}
s << e.jsonString( format, false, pretty?pretty+1:0 );
e = i.next();
if ( e.eoo() )
break;
s << ", ";
}
s << " ]";
break;
}
case DBRef: {
mongo::OID *x = (mongo::OID *) (valuestr() + valuestrsize());
if ( format == TenGen )
s << "Dbref( ";
else
s << "{ \"$ref\" : ";
s << '"' << valuestr() << "\", ";
if ( format != TenGen )
s << "\"$id\" : ";
s << '"' << *x << "\" ";
if ( format == TenGen )
s << ')';
else
s << '}';
break;
}
case jstOID:
if ( format == TenGen ) {
s << "ObjectId( ";
} else {
s << "{ \"$oid\" : ";
}
s << '"' << __oid() << '"';
if ( format == TenGen ) {
s << " )";
} else {
s << " }";
}
break;
case BinData: {
int len = *(int *)( value() );
BinDataType type = BinDataType( *(char *)( (int *)( value() ) + 1 ) );
s << "{ \"$binary\" : \"";
char *start = ( char * )( value() ) + sizeof( int ) + 1;
base64::encode( s , start , len );
s << "\", \"$type\" : \"" << hex;
s.width( 2 );
s.fill( '0' );
//.........这里部分代码省略.........
示例3: run
//.........这里部分代码省略.........
Collection* targetColl = NULL;
while ( !sourceIt->isEOF() ) {
BSONObj o;
{
Client::Context srcCtx( source );
o = sourceIt->getNext().obj();
}
// Insert and check return status of insert.
{
Client::Context ctx( target );
if ( !targetColl )
targetColl = ctx.db()->getCollection( target );
// No logOp necessary because the entire renameCollection command is one logOp.
Status s = targetColl->insertDocument( o, true ).getStatus();
if ( !s.isOK() ) {
insertSuccessful = false;
errmsg = s.toString();
break;
}
}
}
// If inserts were unsuccessful, drop the target collection and return false.
if ( !insertSuccessful ) {
Client::Context ctx( target );
Status s = ctx.db()->dropCollection( target );
if ( !s.isOK() )
errmsg = s.toString();
restoreIndexBuildsOnSource( indexesInProg, source );
return false;
}
// Copy over the indexes to temp storage and then to the target..
vector<BSONObj> copiedIndexes;
bool indexSuccessful = true;
{
Client::Context srcCtx( source );
Collection* sourceColl = srcCtx.db()->getCollection( source );
IndexCatalog::IndexIterator sourceIndIt =
sourceColl->getIndexCatalog()->getIndexIterator( true );
while ( sourceIndIt.more() ) {
BSONObj currIndex = sourceIndIt.next()->infoObj();
// Process the source index.
BSONObjBuilder b;
BSONObjIterator i( currIndex );
while( i.moreWithEOO() ) {
BSONElement e = i.next();
if ( e.eoo() )
break;
else if ( strcmp( e.fieldName(), "ns" ) == 0 )
b.append( "ns", target );
else
b.append( e );
}
BSONObj newIndex = b.obj();
copiedIndexes.push_back( newIndex );
}
}
{
Client::Context ctx( target );
if ( !targetColl )
targetColl = ctx.db()->getCollection( target );
for ( vector<BSONObj>::iterator it = copiedIndexes.begin();
it != copiedIndexes.end(); ++it ) {
Status s = targetColl->getIndexCatalog()->createIndex( *it, true );
if ( !s.isOK() ) {
indexSuccessful = false;
errmsg = s.toString();
break;
}
}
// If indexes were unsuccessful, drop the target collection and return false.
if ( !indexSuccessful ) {
Status s = ctx.db()->dropCollection( target );
if ( !s.isOK() )
errmsg = s.toString();
restoreIndexBuildsOnSource( indexesInProg, source );
return false;
}
}
// Drop the source collection.
{
Client::Context srcCtx( source );
Status s = srcCtx.db()->dropCollection( source );
if ( !s.isOK() ) {
errmsg = s.toString();
restoreIndexBuildsOnSource( indexesInProg, source );
return false;
}
}
return true;
}
示例4: init
void QueryPlanSet::init() {
DEBUGQO( "QueryPlanSet::init " << ns << "\t" << _originalQuery );
_plans.clear();
_mayRecordPlan = true;
_usingPrerecordedPlan = false;
const char *ns = _frsp->ns();
NamespaceDetails *d = nsdetails( ns );
if ( !d || !_frsp->matchPossible() ) {
// Table scan plan, when no matches are possible
_plans.push_back( QueryPlanPtr( new QueryPlan( d, -1, *_frsp, *_originalFrsp, _originalQuery, _order ) ) );
return;
}
BSONElement hint = _hint.firstElement();
if ( !hint.eoo() ) {
_mayRecordPlan = false;
IndexDetails *id = parseHint( hint, d );
if ( id ) {
addHint( *id );
}
else {
massert( 10366 , "natural order cannot be specified with $min/$max", _min.isEmpty() && _max.isEmpty() );
// Table scan plan
_plans.push_back( QueryPlanPtr( new QueryPlan( d, -1, *_frsp, *_originalFrsp, _originalQuery, _order ) ) );
}
return;
}
if ( !_min.isEmpty() || !_max.isEmpty() ) {
string errmsg;
BSONObj keyPattern;
IndexDetails *idx = indexDetailsForRange( ns, errmsg, _min, _max, keyPattern );
massert( 10367 , errmsg, idx );
_plans.push_back( QueryPlanPtr( new QueryPlan( d, d->idxNo(*idx), *_frsp, *_originalFrsp, _originalQuery, _order, _min, _max ) ) );
return;
}
if ( isSimpleIdQuery( _originalQuery ) ) {
int idx = d->findIdIndex();
if ( idx >= 0 ) {
_usingPrerecordedPlan = true;
_mayRecordPlan = false;
_plans.push_back( QueryPlanPtr( new QueryPlan( d , idx , *_frsp , *_originalFrsp , _originalQuery, _order ) ) );
return;
}
}
if ( _originalQuery.isEmpty() && _order.isEmpty() ) {
_plans.push_back( QueryPlanPtr( new QueryPlan( d, -1, *_frsp, *_originalFrsp, _originalQuery, _order ) ) );
return;
}
DEBUGQO( "\t special : " << _frsp->getSpecial() );
if ( _frsp->getSpecial().size() ) {
_special = _frsp->getSpecial();
NamespaceDetails::IndexIterator i = d->ii();
while( i.more() ) {
int j = i.pos();
IndexDetails& ii = i.next();
const IndexSpec& spec = ii.getSpec();
if ( spec.getTypeName() == _special && spec.suitability( _originalQuery , _order ) ) {
_usingPrerecordedPlan = true;
_mayRecordPlan = false;
_plans.push_back( QueryPlanPtr( new QueryPlan( d , j , *_frsp , *_originalFrsp , _originalQuery, _order ,
BSONObj() , BSONObj() , _special ) ) );
return;
}
}
uassert( 13038 , (string)"can't find special index: " + _special + " for: " + _originalQuery.toString() , 0 );
}
if ( _honorRecordedPlan ) {
pair< BSONObj, long long > best = QueryUtilIndexed::bestIndexForPatterns( *_frsp, _order );
BSONObj bestIndex = best.first;
long long oldNScanned = best.second;
if ( !bestIndex.isEmpty() ) {
QueryPlanPtr p;
_oldNScanned = oldNScanned;
if ( !strcmp( bestIndex.firstElement().fieldName(), "$natural" ) ) {
// Table scan plan
p.reset( new QueryPlan( d, -1, *_frsp, *_originalFrsp, _originalQuery, _order ) );
}
NamespaceDetails::IndexIterator i = d->ii();
while( i.more() ) {
int j = i.pos();
IndexDetails& ii = i.next();
if( ii.keyPattern().woCompare(bestIndex) == 0 ) {
p.reset( new QueryPlan( d, j, *_frsp, *_originalFrsp, _originalQuery, _order ) );
}
}
massert( 10368 , "Unable to locate previously recorded index", p.get() );
if ( !( _bestGuessOnly && p->scanAndOrderRequired() ) ) {
_usingPrerecordedPlan = true;
_mayRecordPlan = false;
_plans.push_back( p );
return;
}
//.........这里部分代码省略.........
示例5: getKeys
void FTSIndexFormat::getKeys(const FTSSpec& spec, const BSONObj& obj, BSONObjSet* keys) {
int extraSize = 0;
vector<BSONElement> extrasBefore;
vector<BSONElement> extrasAfter;
// compute the non FTS key elements
for (unsigned i = 0; i < spec.numExtraBefore(); i++) {
BSONElement e = dps::extractElementAtPath(obj, spec.extraBefore(i));
if (e.eoo())
e = nullElt;
uassert(16675, "cannot have a multi-key as a prefix to a text index", e.type() != Array);
extrasBefore.push_back(e);
extraSize += e.size();
}
for (unsigned i = 0; i < spec.numExtraAfter(); i++) {
BSONElement e = dps::extractElementAtPath(obj, spec.extraAfter(i));
if (e.eoo())
e = nullElt;
extrasAfter.push_back(e);
extraSize += e.size();
}
TermFrequencyMap term_freqs;
spec.scoreDocument(obj, &term_freqs);
// create index keys from raw scores
// only 1 per string
uassert(16732,
mongoutils::str::stream() << "too many unique keys for a single document to"
<< " have a text index, max is "
<< term_freqs.size()
<< obj["_id"],
term_freqs.size() <= 400000);
long long keyBSONSize = 0;
const int MaxKeyBSONSizeMB = 4;
for (TermFrequencyMap::const_iterator i = term_freqs.begin(); i != term_freqs.end(); ++i) {
const string& term = i->first;
double weight = i->second;
// guess the total size of the btree entry based on the size of the weight, term tuple
int guess = 5 /* bson overhead */ + 10 /* weight */ + 8 /* term overhead */ +
/* term size (could be truncated/hashed) */
guessTermSize(term, spec.getTextIndexVersion()) + extraSize;
BSONObjBuilder b(guess); // builds a BSON object with guess length.
for (unsigned k = 0; k < extrasBefore.size(); k++) {
b.appendAs(extrasBefore[k], "");
}
_appendIndexKey(b, weight, term, spec.getTextIndexVersion());
for (unsigned k = 0; k < extrasAfter.size(); k++) {
b.appendAs(extrasAfter[k], "");
}
BSONObj res = b.obj();
verify(guess >= res.objsize());
keys->insert(res);
keyBSONSize += res.objsize();
uassert(16733,
mongoutils::str::stream()
<< "trying to index text where term list is too big, max is "
<< MaxKeyBSONSizeMB
<< "mb "
<< obj["_id"],
keyBSONSize <= (MaxKeyBSONSizeMB * 1024 * 1024));
}
}
示例6: _badValue
Status V2PrivilegeDocumentParser::checkValidPrivilegeDocument(const StringData& dbname,
const BSONObj& doc) const {
BSONElement userElement = doc[AuthorizationManager::USER_NAME_FIELD_NAME];
BSONElement userSourceElement = doc[AuthorizationManager::USER_SOURCE_FIELD_NAME];
BSONElement credentialsElement = doc[CREDENTIALS_FIELD_NAME];
BSONElement rolesElement = doc[ROLES_FIELD_NAME];
BSONElement delegatableRolesElement = doc[DELEGATABLE_ROLES_FIELD_NAME];
// Validate the "user" element.
if (userElement.type() != String)
return _badValue("User document needs 'user' field to be a string", 0);
if (makeStringDataFromBSONElement(userElement).empty())
return _badValue("User document needs 'user' field to be non-empty", 0);
// Validate the "userSource" element
if (userSourceElement.type() != String ||
makeStringDataFromBSONElement(userSourceElement).empty()) {
return _badValue("User document needs 'userSource' field to be a non-empty string", 0);
}
StringData userSourceStr = makeStringDataFromBSONElement(userSourceElement);
if (!NamespaceString::validDBName(userSourceStr) && userSourceStr != "$external") {
return _badValue(mongoutils::str::stream() << "'" << userSourceStr <<
"' is not a valid value for the userSource field.",
0);
}
if (userSourceStr != dbname) {
return _badValue(mongoutils::str::stream() << "userSource '" << userSourceStr <<
"' does not match database '" << dbname << "'", 0);
}
// Validate the "credentials" element
if (credentialsElement.eoo() && userSourceStr != "$external") {
return _badValue("User document needs 'credentials' field unless userSource is "
"'$external'",
0);
}
if (!credentialsElement.eoo()) {
if (credentialsElement.type() != Object) {
return _badValue("User document needs 'credentials' field to be an object", 0);
}
BSONObj credentialsObj = credentialsElement.Obj();
if (credentialsObj.isEmpty()) {
return _badValue("User document needs 'credentials' field to be a non-empty object",
0);
}
BSONElement MongoCRElement = credentialsObj[MONGODB_CR_CREDENTIAL_FIELD_NAME];
if (!MongoCRElement.eoo() && (MongoCRElement.type() != String ||
makeStringDataFromBSONElement(MongoCRElement).empty())) {
return _badValue("MONGODB-CR credential must to be a non-empty string, if present",
0);
}
}
// Validate the "roles" element.
Status status = _checkV2RolesArray(rolesElement);
if (!status.isOK())
return status;
// Validate the "delegatableRoles" element.
status = _checkV2RolesArray(delegatableRolesElement);
if (!status.isOK())
return status;
return Status::OK();
}
示例7: parseBSON
bool BatchedCommandResponse::parseBSON(const BSONObj& source, string* errMsg) {
clear();
std::string dummy;
if (!errMsg)
errMsg = &dummy;
_status = getStatusFromCommandResult(source);
_isStatusSet = true;
// 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;
auto 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);
WriteConcernErrorDetail* wcError = NULL;
fieldState = FieldParser::extract(source, writeConcernError, &wcError, errMsg);
if (fieldState == FieldParser::FIELD_INVALID)
return false;
_wcErrDetails.reset(wcError);
return true;
}
示例8: run
bool run(OperationContext* txn,
const string& dbname,
BSONObj& cmdObj,
int,
string& errmsg,
BSONObjBuilder& result) {
if (!cmdObj["start"].eoo()) {
errmsg = "using deprecated 'start' argument to geoNear";
return false;
}
const NamespaceString nss(parseNs(dbname, cmdObj));
AutoGetCollectionForRead ctx(txn, nss);
Collection* collection = ctx.getCollection();
if ( !collection ) {
errmsg = "can't find ns";
return false;
}
IndexCatalog* indexCatalog = collection->getIndexCatalog();
// cout << "raw cmd " << cmdObj.toString() << endl;
// We seek to populate this.
string nearFieldName;
bool using2DIndex = false;
if (!getFieldName(txn, collection, indexCatalog, &nearFieldName, &errmsg, &using2DIndex)) {
return false;
}
PointWithCRS point;
uassert(17304, "'near' field must be point",
GeoParser::parseQueryPoint(cmdObj["near"], &point).isOK());
bool isSpherical = cmdObj["spherical"].trueValue();
if (!using2DIndex) {
uassert(17301, "2dsphere index must have spherical: true", isSpherical);
}
// Build the $near expression for the query.
BSONObjBuilder nearBob;
if (isSpherical) {
nearBob.append("$nearSphere", cmdObj["near"].Obj());
}
else {
nearBob.append("$near", cmdObj["near"].Obj());
}
if (!cmdObj["maxDistance"].eoo()) {
uassert(17299, "maxDistance must be a number",cmdObj["maxDistance"].isNumber());
nearBob.append("$maxDistance", cmdObj["maxDistance"].number());
}
if (!cmdObj["minDistance"].eoo()) {
uassert(17298, "minDistance doesn't work on 2d index", !using2DIndex);
uassert(17300, "minDistance must be a number",cmdObj["minDistance"].isNumber());
nearBob.append("$minDistance", cmdObj["minDistance"].number());
}
if (!cmdObj["uniqueDocs"].eoo()) {
warning() << nss << ": ignoring deprecated uniqueDocs option in geoNear command";
}
// And, build the full query expression.
BSONObjBuilder queryBob;
queryBob.append(nearFieldName, nearBob.obj());
if (!cmdObj["query"].eoo() && cmdObj["query"].isABSONObj()) {
queryBob.appendElements(cmdObj["query"].Obj());
}
BSONObj rewritten = queryBob.obj();
// cout << "rewritten query: " << rewritten.toString() << endl;
long long numWanted = 100;
const char* limitName = !cmdObj["num"].eoo() ? "num" : "limit";
BSONElement eNumWanted = cmdObj[limitName];
if (!eNumWanted.eoo()) {
uassert(17303, "limit must be number", eNumWanted.isNumber());
numWanted = eNumWanted.safeNumberLong();
uassert(17302, "limit must be >=0", numWanted >= 0);
}
bool includeLocs = false;
if (!cmdObj["includeLocs"].eoo()) {
includeLocs = cmdObj["includeLocs"].trueValue();
}
double distanceMultiplier = 1.0;
BSONElement eDistanceMultiplier = cmdObj["distanceMultiplier"];
if (!eDistanceMultiplier.eoo()) {
uassert(17296, "distanceMultiplier must be a number", eDistanceMultiplier.isNumber());
distanceMultiplier = eDistanceMultiplier.number();
uassert(17297, "distanceMultiplier must be non-negative", distanceMultiplier >= 0);
}
BSONObj projObj = BSON("$pt" << BSON("$meta" << LiteParsedQuery::metaGeoNearPoint) <<
"$dis" << BSON("$meta" << LiteParsedQuery::metaGeoNearDistance));
CanonicalQuery* cq;
//.........这里部分代码省略.........
示例9: analyzeSort
// static
QuerySolutionNode* QueryPlannerAnalysis::analyzeSort(const CanonicalQuery& query,
const QueryPlannerParams& params,
QuerySolutionNode* solnRoot,
bool* blockingSortOut) {
*blockingSortOut = false;
const BSONObj& sortObj = query.getParsed().getSort();
if (sortObj.isEmpty()) {
return solnRoot;
}
// TODO: We could check sortObj for any projections other than :1 and :-1
// and short-cut some of this.
// If the sort is $natural, we ignore it, assuming that the caller has detected that and
// outputted a collscan to satisfy the desired order.
BSONElement natural = sortObj.getFieldDotted("$natural");
if (!natural.eoo()) {
return solnRoot;
}
// See if solnRoot gives us the sort. If so, we're done.
BSONObjSet sorts = solnRoot->getSort();
// If the sort we want is in the set of sort orders provided already, bail out.
if (sorts.end() != sorts.find(sortObj)) {
return solnRoot;
}
// Sort is not provided. See if we provide the reverse of our sort pattern.
// If so, we can reverse the scan direction(s).
BSONObj reverseSort = QueryPlannerCommon::reverseSortObj(sortObj);
if (sorts.end() != sorts.find(reverseSort)) {
QueryPlannerCommon::reverseScans(solnRoot);
QLOG() << "Reversing ixscan to provide sort. Result: "
<< solnRoot->toString() << endl;
return solnRoot;
}
// Sort not provided, can't reverse scans to get the sort. One last trick: We can "explode"
// index scans over point intervals to an OR of sub-scans in order to pull out a sort.
// Let's try this.
if (explodeForSort(query, params, &solnRoot)) {
return solnRoot;
}
// If we're here, we need to add a sort stage.
// If we're not allowed to put a blocking sort in, bail out.
if (params.options & QueryPlannerParams::NO_BLOCKING_SORT) {
delete solnRoot;
return NULL;
}
// Add a fetch stage so we have the full object when we hit the sort stage. TODO: Can we
// pull the values that we sort by out of the key and if so in what cases? Perhaps we can
// avoid a fetch.
if (!solnRoot->fetched()) {
FetchNode* fetch = new FetchNode();
fetch->children.push_back(solnRoot);
solnRoot = fetch;
}
// And build the full sort stage.
SortNode* sort = new SortNode();
sort->pattern = sortObj;
sort->query = query.getParsed().getFilter();
sort->children.push_back(solnRoot);
solnRoot = sort;
// When setting the limit on the sort, we need to consider both
// the limit N and skip count M. The sort should return an ordered list
// N + M items so that the skip stage can discard the first M results.
if (0 != query.getParsed().getNumToReturn()) {
// Overflow here would be bad and could cause a nonsense limit. Cast
// skip and limit values to unsigned ints to make sure that the
// sum is never stored as signed. (See SERVER-13537).
sort->limit = size_t(query.getParsed().getNumToReturn()) +
size_t(query.getParsed().getSkip());
// This is a SORT with a limit. The wire protocol has a single quantity
// called "numToReturn" which could mean either limit or batchSize.
// We have no idea what the client intended. One way to handle the ambiguity
// of a limited OR stage is to use the SPLIT_LIMITED_SORT hack.
//
// If numToReturn is really a limit, then we want to add a limit to this
// SORT stage, and hence perform a topK.
//
// If numToReturn is really a batchSize, then we want to perform a regular
// blocking sort.
//
// Since we don't know which to use, just join the two options with an OR,
// with the topK first. If the client wants a limit, they'll get the efficiency
// of topK. If they want a batchSize, the other OR branch will deliver the missing
// results. The OR stage handles deduping.
if (params.options & QueryPlannerParams::SPLIT_LIMITED_SORT
&& !QueryPlannerCommon::hasNode(query.root(), MatchExpression::TEXT)
&& !QueryPlannerCommon::hasNode(query.root(), MatchExpression::GEO)
&& !QueryPlannerCommon::hasNode(query.root(), MatchExpression::GEO_NEAR)) {
//.........这里部分代码省略.........
示例10: addTriggeredSubscriptions
//.........这里部分代码省略.........
"enType = "+typeJsString+ ";" +
"for (var i=0; i < this."+CASUB_ENTITIES+".length; i++) {" +
"if (this."+CASUB_ENTITIES+"[i]."+CASUB_ENTITY_ISPATTERN+" == \"true\") {" +
"for (var j=0; j < enId.length; j++) {" +
"if (enId[j].match(this."+CASUB_ENTITIES+"[i]."+CASUB_ENTITY_ID+") && this."+CASUB_ENTITIES+"[i]."+CASUB_ENTITY_TYPE+" == enType[j]) {" +
"return true; " +
"}" +
"}" +
"}" +
"}" +
"return false; " +
"}";
LM_T(LmtMongo, ("JS function: %s", function.c_str()));
std::string entPatternQ = CSUB_ENTITIES "." CSUB_ENTITY_ISPATTERN;
BSONObjBuilder queryPattern;
queryPattern.append(entPatternQ, "true");
queryPattern.append(CASUB_EXPIRATION, BSON("$gt" << (long long) getCurrentTime()));
queryPattern.appendCode("$where", function);
BSONObj query = BSON("$or" << BSON_ARRAY(queryNoPattern.obj() << queryPattern.obj()));
/* Do the query */
auto_ptr<DBClientCursor> cursor;
LM_T(LmtMongo, ("query() in '%s' collection: '%s'", getSubscribeContextAvailabilityCollectionName(tenant).c_str(), query.toString().c_str()));
try
{
connection = getMongoConnection();
cursor = connection->query(getSubscribeContextAvailabilityCollectionName(tenant).c_str(), query);
/*
* We have observed that in some cases of DB errors (e.g. the database daemon is down) instead of
* raising an exception, the query() method sets the cursor to NULL. In this case, we raise the
* exception ourselves
*/
if (cursor.get() == NULL)
{
throw DBException("Null cursor from mongo (details on this is found in the source code)", 0);
}
releaseMongoConnection(connection);
LM_I(("Database Operation Successful (%s)", query.toString().c_str()));
}
catch (const DBException &e)
{
releaseMongoConnection(connection);
err = std::string("collection: ") + getSubscribeContextAvailabilityCollectionName(tenant).c_str() +
" - query(): " + query.toString() +
" - exception: " + e.what();
LM_E(("Database Error (%s)", err.c_str()));
return false;
}
catch (...)
{
releaseMongoConnection(connection);
err = std::string("collection: ") + getSubscribeContextAvailabilityCollectionName(tenant).c_str() +
" - query(): " + query.toString() +
" - exception: " + "generic";
LM_E(("Database Error (%s)", err.c_str()));
return false;
}
/* For each one of the subscriptions found, add it to the map (if not already there) */
while (cursor->more())
{
BSONObj sub = cursor->next();
BSONElement idField = sub.getField("_id");
//
// BSONElement::eoo returns true if 'not found', i.e. the field "_id" doesn't exist in 'sub'
//
// Now, if 'sub.getField("_id")' is not found, if we continue, calling OID() on it, then we get
// an exception and the broker crashes.
//
if (idField.eoo() == true)
{
LM_E(("Database Error (error retrieving _id field in doc: %s)", sub.toString().c_str()));
continue;
}
std::string subIdStr = idField.OID().toString();
if (subs.count(subIdStr) == 0) {
LM_T(LmtMongo, ("adding subscription: '%s'", sub.toString().c_str()));
TriggeredSubscription* trigs = new TriggeredSubscription(sub.hasField(CASUB_FORMAT) ? stringToFormat(STR_FIELD(sub, CASUB_FORMAT)) : XML,
STR_FIELD(sub, CASUB_REFERENCE),
subToAttributeList(sub));
subs.insert(std::pair<string, TriggeredSubscription*>(subIdStr, trigs));
}
}
return true;
}
示例11: getUserDescription
Status AuthzManagerExternalStateMongos::getUserDescription(OperationContext* opCtx,
const UserName& userName,
BSONObj* result) {
if (!shouldUseRolesFromConnection(opCtx, userName)) {
BSONObj usersInfoCmd =
BSON("usersInfo" << BSON_ARRAY(BSON(AuthorizationManager::USER_NAME_FIELD_NAME
<< userName.getUser()
<< AuthorizationManager::USER_DB_FIELD_NAME
<< userName.getDB()))
<< "showPrivileges"
<< true
<< "showCredentials"
<< true
<< "showAuthenticationRestrictions"
<< true);
BSONObjBuilder builder;
const bool ok = Grid::get(opCtx)->catalogClient()->runUserManagementReadCommand(
opCtx, "admin", usersInfoCmd, &builder);
BSONObj cmdResult = builder.obj();
if (!ok) {
return getStatusFromCommandResult(cmdResult);
}
std::vector<BSONElement> foundUsers = cmdResult["users"].Array();
if (foundUsers.size() == 0) {
return Status(ErrorCodes::UserNotFound,
"User \"" + userName.toString() + "\" not found");
}
if (foundUsers.size() > 1) {
return Status(ErrorCodes::UserDataInconsistent,
str::stream() << "Found multiple users on the \"" << userName.getDB()
<< "\" database with name \""
<< userName.getUser()
<< "\"");
}
*result = foundUsers[0].Obj().getOwned();
return Status::OK();
} else {
// Obtain privilege information from the config servers for all roles acquired from the X509
// certificate.
BSONArrayBuilder userRolesBuilder;
auto& sslPeerInfo = SSLPeerInfo::forSession(opCtx->getClient()->session());
for (const RoleName& role : sslPeerInfo.roles) {
userRolesBuilder.append(BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< role.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< role.getDB()));
}
BSONArray providedRoles = userRolesBuilder.arr();
BSONObj rolesInfoCmd = BSON("rolesInfo" << providedRoles << "showPrivileges"
<< "asUserFragment");
BSONObjBuilder cmdResultBuilder;
const bool cmdOk = Grid::get(opCtx)->catalogClient()->runUserManagementReadCommand(
opCtx, "admin", rolesInfoCmd, &cmdResultBuilder);
BSONObj cmdResult = cmdResultBuilder.obj();
if (!cmdOk || !cmdResult["userFragment"].ok()) {
return Status(ErrorCodes::FailedToParse,
"Unable to get resolved X509 roles from config server: " +
getStatusFromCommandResult(cmdResult).toString());
}
cmdResult = cmdResult["userFragment"].Obj().getOwned();
BSONElement userRoles = cmdResult["roles"];
BSONElement userInheritedRoles = cmdResult["inheritedRoles"];
BSONElement userInheritedPrivileges = cmdResult["inheritedPrivileges"];
if (userRoles.eoo() || userInheritedRoles.eoo() || userInheritedPrivileges.eoo() ||
!userRoles.isABSONObj() || !userInheritedRoles.isABSONObj() ||
!userInheritedPrivileges.isABSONObj()) {
return Status(
ErrorCodes::UserDataInconsistent,
"Recieved malformed response to request for X509 roles from config server");
}
*result = BSON("_id" << userName.getUser() << "user" << userName.getUser() << "db"
<< userName.getDB()
<< "credentials"
<< BSON("external" << true)
<< "roles"
<< BSONArray(cmdResult["roles"].Obj())
<< "inheritedRoles"
<< BSONArray(cmdResult["inheritedRoles"].Obj())
<< "inheritedPrivileges"
<< BSONArray(cmdResult["inheritedPrivileges"].Obj()));
return Status::OK();
}
}
示例12: initialize
Status MemberConfig::initialize(const BSONObj& mcfg, ReplicaSetTagConfig* tagConfig) {
Status status = bsonCheckOnlyHasFields(
"replica set member configuration", mcfg, kLegalMemberConfigFieldNames);
if (!status.isOK())
return status;
//
// Parse _id field.
//
BSONElement idElement = mcfg[kIdFieldName];
if (idElement.eoo()) {
return Status(ErrorCodes::NoSuchKey, str::stream() << kIdFieldName << " field is missing");
}
if (!idElement.isNumber()) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << kIdFieldName << " field has non-numeric type "
<< typeName(idElement.type()));
}
_id = idElement.numberInt();
//
// Parse h field.
//
std::string hostAndPortString;
status = bsonExtractStringField(mcfg, kHostFieldName, &hostAndPortString);
if (!status.isOK())
return status;
boost::trim(hostAndPortString);
status = _host.initialize(hostAndPortString);
if (!status.isOK())
return status;
if (!_host.hasPort()) {
// make port explicit even if default.
_host = HostAndPort(_host.host(), _host.port());
}
//
// Parse votes field.
//
BSONElement votesElement = mcfg[kVotesFieldName];
if (votesElement.eoo()) {
_votes = kVotesFieldDefault;
} else if (votesElement.isNumber()) {
_votes = votesElement.numberInt();
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << kVotesFieldName << " field value has non-numeric type "
<< typeName(votesElement.type()));
}
//
// Parse priority field.
//
BSONElement priorityElement = mcfg[kPriorityFieldName];
if (priorityElement.eoo()) {
_priority = kPriorityFieldDefault;
} else if (priorityElement.isNumber()) {
_priority = priorityElement.numberDouble();
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << kPriorityFieldName << " field has non-numeric type "
<< typeName(priorityElement.type()));
}
//
// Parse arbiterOnly field.
//
status = bsonExtractBooleanFieldWithDefault(
mcfg, kArbiterOnlyFieldName, kArbiterOnlyFieldDefault, &_arbiterOnly);
if (!status.isOK())
return status;
//
// Parse slaveDelay field.
//
BSONElement slaveDelayElement = mcfg[kSlaveDelayFieldName];
if (slaveDelayElement.eoo()) {
_slaveDelay = kSlaveDelayFieldDefault;
} else if (slaveDelayElement.isNumber()) {
_slaveDelay = Seconds(slaveDelayElement.numberInt());
} else {
return Status(ErrorCodes::TypeMismatch,
str::stream() << kSlaveDelayFieldName << " field value has non-numeric type "
<< typeName(slaveDelayElement.type()));
}
//
// Parse hidden field.
//
status =
bsonExtractBooleanFieldWithDefault(mcfg, kHiddenFieldName, kHiddenFieldDefault, &_hidden);
if (!status.isOK())
return status;
//
// Parse buildIndexes field.
//
status = bsonExtractBooleanFieldWithDefault(
mcfg, kBuildIndexesFieldName, kBuildIndexesFieldDefault, &_buildIndexes);
if (!status.isOK())
//.........这里部分代码省略.........
示例13: parse
Status WriteConcernOptions::parse(const BSONObj& obj) {
reset();
if (obj.isEmpty()) {
return Status(ErrorCodes::FailedToParse, "write concern object cannot be empty");
}
BSONElement jEl;
BSONElement fsyncEl;
BSONElement wEl;
for (auto e : obj) {
const auto fieldName = e.fieldNameStringData();
if (fieldName == kJFieldName) {
jEl = e;
if (!jEl.isNumber() && jEl.type() != Bool) {
return Status(ErrorCodes::FailedToParse, "j must be numeric or a boolean value");
}
} else if (fieldName == kFSyncFieldName) {
fsyncEl = e;
if (!fsyncEl.isNumber() && fsyncEl.type() != Bool) {
return Status(ErrorCodes::FailedToParse,
"fsync must be numeric or a boolean value");
}
} else if (fieldName == kWFieldName) {
wEl = e;
} else if (fieldName == kWTimeoutFieldName) {
wTimeout = e.numberInt();
} else if (fieldName == kWElectionIdFieldName) {
// Ignore.
} else if (fieldName == kWOpTimeFieldName) {
// Ignore.
} else if (fieldName.equalCaseInsensitive(kGetLastErrorFieldName)) {
// Ignore GLE field.
} else {
return Status(ErrorCodes::FailedToParse,
str::stream() << "unrecognized write concern field: " << fieldName);
}
}
const bool j = jEl.trueValue();
const bool fsync = fsyncEl.trueValue();
if (j && fsync)
return Status(ErrorCodes::FailedToParse, "fsync and j options cannot be used together");
if (j) {
syncMode = SyncMode::JOURNAL;
} else if (fsync) {
syncMode = SyncMode::FSYNC;
} else if (!jEl.eoo()) {
syncMode = SyncMode::NONE;
}
if (wEl.isNumber()) {
wNumNodes = wEl.numberInt();
} else if (wEl.type() == String) {
wMode = wEl.valuestrsafe();
} else if (wEl.eoo() || wEl.type() == jstNULL || wEl.type() == Undefined) {
wNumNodes = 1;
} else {
return Status(ErrorCodes::FailedToParse, "w has to be a number or a string");
}
return Status::OK();
}
示例14: _handleOneLoop
INT32 _fmpController::_handleOneLoop( const BSONObj &obj,
INT32 step )
{
INT32 rc = SDB_OK ;
BSONObj res ;
if ( FMP_CONTROL_STEP_BEGIN == step )
{
UINT32 seqID = 1 ;
BSONElement beSeq = obj.getField( FMP_SEQ_ID ) ;
if ( beSeq.isNumber() )
{
seqID = (UINT32)beSeq.numberInt() ;
}
BSONElement diag = obj.getField( FMP_DIAG_PATH ) ;
if ( !diag.eoo() && String == diag.type() )
{
CHAR diaglogShort[ OSS_MAX_PATHSIZE + 1 ] = { 0 } ;
ossSnprintf( diaglogShort, OSS_MAX_PATHSIZE, "%s_%u.%s",
PD_FMP_DIAGLOG_PREFIX, seqID, PD_FMP_DIAGLOG_SUBFIX ) ;
CHAR diaglog[ OSS_MAX_PATHSIZE + 1 ] = {0} ;
engine::utilBuildFullPath( diag.valuestrsafe(), diaglogShort,
OSS_MAX_PATHSIZE, diaglog ) ;
sdbEnablePD( diaglog ) ;
}
BSONElement localService = obj.getField( FMP_LOCAL_SERVICE ) ;
if ( !localService.eoo() && String == localService.type() &&
0 == ossStrlen(FMP_COORD_SERVICE) )
{
ossMemcpy( FMP_COORD_SERVICE, localService.valuestrsafe(),
ossStrlen( localService.valuestrsafe() ) + 1 ) ;
}
BSONElement localUser = obj.getField( FMP_LOCAL_USERNAME ) ;
if ( String == localUser.type() )
{
ossStrncpy( g_UserName, localUser.valuestrsafe(),
OSS_MAX_PATHSIZE ) ;
}
BSONElement localPass = obj.getField( FMP_LOCAL_PASSWORD ) ;
if ( String == localPass.type() )
{
ossStrncpy( g_Password, localPass.valuestrsafe(),
OSS_MAX_PATHSIZE ) ;
}
BSONElement fType = obj.getField( FMP_FUNC_TYPE ) ;
if ( fType.eoo() )
{
rc = _createVM( FMP_FUNC_TYPE_JS ) ;
if ( SDB_OK != rc )
{
PD_LOG(PDERROR, "failed to create vm:%d", rc ) ;
res = BSON( FMP_ERR_MSG << "failed to create vm" <<
FMP_RES_CODE << rc ) ;
goto error ;
}
rc = _vm->init( obj ) ;
if ( SDB_OK != rc )
{
PD_LOG(PDERROR, "failed to init vm:%d", rc ) ;
res = BSON( FMP_ERR_MSG << "failed to init vm" <<
FMP_RES_CODE << rc ) ;
goto error ;
}
}
else if ( NumberInt != fType.type() )
{
PD_LOG( PDERROR, "invalid type of func type:%s",
fType.toString().c_str() ) ;
rc = SDB_SYS ;
res = BSON( FMP_ERR_MSG << "invalid type of func type" <<
FMP_RES_CODE << SDB_SYS ) ;
goto error ;
}
else
{
rc = _createVM( fType.Int() ) ;
if ( SDB_OK != rc )
{
PD_LOG(PDERROR, "failed to create vm:%d", rc ) ;
res = BSON( FMP_ERR_MSG << "failed to create vm" <<
FMP_RES_CODE << rc ) ;
goto error ;
}
rc = _vm->init( obj ) ;
if ( SDB_OK != rc )
{
PD_LOG(PDERROR, "failed to init vm:%d", rc ) ;
res = BSON( FMP_ERR_MSG << "failed to init vm" <<
FMP_RES_CODE << rc ) ;
goto error ;
}
}
}
else if ( FMP_CONTROL_STEP_DOWNLOAD == step )
{
SDB_ASSERT( NULL != _vm, "impossible" ) ;
rc = _vm->eval( obj, res ) ;
//.........这里部分代码省略.........
示例15: run
bool run(const string& dbname, BSONObj& jsobj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl ) {
if ( !globalScriptEngine ) {
errmsg = "server-side JavaScript execution is disabled";
return false;
}
/* db.$cmd.findOne( { group : <p> } ) */
const BSONObj& p = jsobj.firstElement().embeddedObjectUserCheck();
BSONObj q;
if ( p["cond"].type() == Object )
q = p["cond"].embeddedObject();
else if ( p["condition"].type() == Object )
q = p["condition"].embeddedObject();
else
q = getQuery( p );
if ( p["ns"].type() != String ) {
errmsg = "ns has to be set";
return false;
}
string ns = dbname + "." + p["ns"].String();
BSONObj key;
string keyf;
if ( p["key"].type() == Object ) {
key = p["key"].embeddedObjectUserCheck();
if ( ! p["$keyf"].eoo() ) {
errmsg = "can't have key and $keyf";
return false;
}
}
else if ( p["$keyf"].type() ) {
keyf = p["$keyf"]._asCode();
}
else {
// no key specified, will use entire object as key
}
BSONElement reduce = p["$reduce"];
if ( reduce.eoo() ) {
errmsg = "$reduce has to be set";
return false;
}
BSONElement initial = p["initial"];
if ( initial.type() != Object ) {
errmsg = "initial has to be an object";
return false;
}
string finalize;
if (p["finalize"].type())
finalize = p["finalize"]._asCode();
return group( dbname , ns , q ,
key , keyf , reduce._asCode() , reduce.type() != CodeWScope ? 0 : reduce.codeWScopeScopeDataUnsafe() ,
initial.embeddedObject() , finalize ,
errmsg , result );
}