PageRenderTime 73ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 1ms

/db/ops/query.cpp

https://bitbucket.org/drainware/mongodb
C++ | 1020 lines | 815 code | 131 blank | 74 comment | 211 complexity | 70deb3818465bacb4c9d831c0e9e9e5d MD5 | raw file
Possible License(s): BSD-3-Clause
  1. // query.cpp
  2. /**
  3. * Copyright (C) 2008 10gen Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License, version 3,
  7. * as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU Affero General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "pch.h"
  18. #include "query.h"
  19. #include "../pdfile.h"
  20. #include "../jsobjmanipulator.h"
  21. #include "../../bson/util/builder.h"
  22. #include <time.h>
  23. #include "../introspect.h"
  24. #include "../btree.h"
  25. #include "../../util/lruishmap.h"
  26. #include "../json.h"
  27. #include "../repl.h"
  28. #include "../replutil.h"
  29. #include "../scanandorder.h"
  30. #include "../security.h"
  31. #include "../curop-inl.h"
  32. #include "../commands.h"
  33. #include "../queryoptimizer.h"
  34. #include "../lasterror.h"
  35. #include "../../s/d_logic.h"
  36. #include "../repl_block.h"
  37. #include "../../server.h"
  38. namespace mongo {
  39. /* We cut off further objects once we cross this threshold; thus, you might get
  40. a little bit more than this, it is a threshold rather than a limit.
  41. */
  42. const int MaxBytesToReturnToClientAtOnce = 4 * 1024 * 1024;
  43. //ns->query->DiskLoc
  44. // LRUishMap<BSONObj,DiskLoc,5> lrutest(123);
  45. extern bool useCursors;
  46. extern bool useHints;
  47. bool runCommands(const char *ns, BSONObj& jsobj, CurOp& curop, BufBuilder &b, BSONObjBuilder& anObjBuilder, bool fromRepl, int queryOptions) {
  48. try {
  49. return _runCommands(ns, jsobj, b, anObjBuilder, fromRepl, queryOptions);
  50. }
  51. catch ( AssertionException& e ) {
  52. e.getInfo().append( anObjBuilder , "assertion" , "assertionCode" );
  53. curop.debug().exceptionInfo = e.getInfo();
  54. }
  55. anObjBuilder.append("errmsg", "db assertion failure");
  56. anObjBuilder.append("ok", 0.0);
  57. BSONObj x = anObjBuilder.done();
  58. b.appendBuf((void*) x.objdata(), x.objsize());
  59. return true;
  60. }
  61. BSONObj id_obj = fromjson("{\"_id\":1}");
  62. BSONObj empty_obj = fromjson("{}");
  63. //int dump = 0;
  64. /* empty result for error conditions */
  65. QueryResult* emptyMoreResult(long long cursorid) {
  66. BufBuilder b(32768);
  67. b.skip(sizeof(QueryResult));
  68. QueryResult *qr = (QueryResult *) b.buf();
  69. qr->cursorId = 0; // 0 indicates no more data to retrieve.
  70. qr->startingFrom = 0;
  71. qr->len = b.len();
  72. qr->setOperation(opReply);
  73. qr->initializeResultFlags();
  74. qr->nReturned = 0;
  75. b.decouple();
  76. return qr;
  77. }
  78. QueryResult* processGetMore(const char *ns, int ntoreturn, long long cursorid , CurOp& curop, int pass, bool& exhaust ) {
  79. exhaust = false;
  80. ClientCursor::Pointer p(cursorid);
  81. ClientCursor *cc = p.c();
  82. int bufSize = 512 + sizeof( QueryResult ) + MaxBytesToReturnToClientAtOnce;
  83. BufBuilder b( bufSize );
  84. b.skip(sizeof(QueryResult));
  85. int resultFlags = ResultFlag_AwaitCapable;
  86. int start = 0;
  87. int n = 0;
  88. if ( unlikely(!cc) ) {
  89. log() << "getMore: cursorid not found " << ns << " " << cursorid << endl;
  90. cursorid = 0;
  91. resultFlags = ResultFlag_CursorNotFound;
  92. }
  93. else {
  94. // check for spoofing of the ns such that it does not match the one originally there for the cursor
  95. uassert(14833, "auth error", str::equals(ns, cc->ns().c_str()));
  96. if ( pass == 0 )
  97. cc->updateSlaveLocation( curop );
  98. int queryOptions = cc->queryOptions();
  99. curop.debug().query = cc->query();
  100. start = cc->pos();
  101. Cursor *c = cc->c();
  102. c->checkLocation();
  103. DiskLoc last;
  104. scoped_ptr<Projection::KeyOnly> keyFieldsOnly;
  105. if ( cc->modifiedKeys() == false && cc->isMultiKey() == false && cc->fields )
  106. keyFieldsOnly.reset( cc->fields->checkKey( cc->indexKeyPattern() ) );
  107. // This manager may be stale, but it's the state of chunking when the cursor was created.
  108. ShardChunkManagerPtr manager = cc->getChunkManager();
  109. while ( 1 ) {
  110. if ( !c->ok() ) {
  111. if ( c->tailable() ) {
  112. /* when a tailable cursor hits "EOF", ok() goes false, and current() is null. however
  113. advance() can still be retries as a reactivation attempt. when there is new data, it will
  114. return true. that's what we are doing here.
  115. */
  116. if ( c->advance() )
  117. continue;
  118. if( n == 0 && (queryOptions & QueryOption_AwaitData) && pass < 1000 ) {
  119. return 0;
  120. }
  121. break;
  122. }
  123. p.release();
  124. bool ok = ClientCursor::erase(cursorid);
  125. assert(ok);
  126. cursorid = 0;
  127. cc = 0;
  128. break;
  129. }
  130. // in some cases (clone collection) there won't be a matcher
  131. if ( c->matcher() && !c->matcher()->matchesCurrent( c ) ) {
  132. }
  133. else if ( manager && ! manager->belongsToMe( cc ) ){
  134. LOG(2) << "cursor skipping document in un-owned chunk: " << c->current() << endl;
  135. }
  136. else {
  137. if( c->getsetdup(c->currLoc()) ) {
  138. //out() << " but it's a dup \n";
  139. }
  140. else {
  141. last = c->currLoc();
  142. n++;
  143. if ( keyFieldsOnly ) {
  144. fillQueryResultFromObj(b, 0, keyFieldsOnly->hydrate( c->currKey() ) );
  145. }
  146. else {
  147. BSONObj js = c->current();
  148. // show disk loc should be part of the main query, not in an $or clause, so this should be ok
  149. fillQueryResultFromObj(b, cc->fields.get(), js, ( cc->pq.get() && cc->pq->showDiskLoc() ? &last : 0));
  150. }
  151. if ( ( ntoreturn && n >= ntoreturn ) || b.len() > MaxBytesToReturnToClientAtOnce ) {
  152. c->advance();
  153. cc->incPos( n );
  154. break;
  155. }
  156. }
  157. }
  158. c->advance();
  159. if ( ! cc->yieldSometimes( ClientCursor::MaybeCovered ) ) {
  160. ClientCursor::erase(cursorid);
  161. cursorid = 0;
  162. cc = 0;
  163. p.deleted();
  164. break;
  165. }
  166. }
  167. if ( cc ) {
  168. cc->updateLocation();
  169. cc->mayUpgradeStorage();
  170. cc->storeOpForSlave( last );
  171. exhaust = cc->queryOptions() & QueryOption_Exhaust;
  172. }
  173. }
  174. QueryResult *qr = (QueryResult *) b.buf();
  175. qr->len = b.len();
  176. qr->setOperation(opReply);
  177. qr->_resultFlags() = resultFlags;
  178. qr->cursorId = cursorid;
  179. qr->startingFrom = start;
  180. qr->nReturned = n;
  181. b.decouple();
  182. return qr;
  183. }
  184. class CountOp : public QueryOp {
  185. public:
  186. CountOp( const string& ns , const BSONObj &spec ) :
  187. _ns(ns), _capped(false), _count(), _myCount(),
  188. _skip( spec["skip"].numberLong() ),
  189. _limit( spec["limit"].numberLong() ),
  190. _nscanned(),
  191. _bc() {
  192. }
  193. virtual void _init() {
  194. _c = qp().newCursor();
  195. _capped = _c->capped();
  196. if ( qp().exactKeyMatch() && ! matcher( _c )->needRecord() ) {
  197. _query = qp().simplifiedQuery( qp().indexKey() );
  198. _bc = dynamic_cast< BtreeCursor* >( _c.get() );
  199. _bc->forgetEndKey();
  200. }
  201. }
  202. virtual long long nscanned() {
  203. return _c.get() ? _c->nscanned() : _nscanned;
  204. }
  205. virtual bool prepareToYield() {
  206. if ( _c && !_cc ) {
  207. _cc.reset( new ClientCursor( QueryOption_NoCursorTimeout , _c , _ns.c_str() ) );
  208. }
  209. if ( _cc ) {
  210. return _cc->prepareToYield( _yieldData );
  211. }
  212. // no active cursor - ok to yield
  213. return true;
  214. }
  215. virtual void recoverFromYield() {
  216. if ( _cc && !ClientCursor::recoverFromYield( _yieldData ) ) {
  217. _c.reset();
  218. _cc.reset();
  219. if ( _capped ) {
  220. msgassertedNoTrace( 13337, str::stream() << "capped cursor overrun during count: " << _ns );
  221. }
  222. else if ( qp().mustAssertOnYieldFailure() ) {
  223. msgassertedNoTrace( 15891, str::stream() << "CountOp::recoverFromYield() failed to recover: " << _ns );
  224. }
  225. else {
  226. // we don't fail query since we're fine with returning partial data if collection dropped
  227. }
  228. }
  229. }
  230. virtual void next() {
  231. if ( ! _c || !_c->ok() ) {
  232. setComplete();
  233. return;
  234. }
  235. _nscanned = _c->nscanned();
  236. if ( _bc ) {
  237. if ( _firstMatch.isEmpty() ) {
  238. _firstMatch = _bc->currKey().getOwned();
  239. // if not match
  240. if ( _query.woCompare( _firstMatch, BSONObj(), false ) ) {
  241. setComplete();
  242. return;
  243. }
  244. _gotOne();
  245. }
  246. else {
  247. if ( ! _firstMatch.equal( _bc->currKey() ) ) {
  248. setComplete();
  249. return;
  250. }
  251. _gotOne();
  252. }
  253. }
  254. else {
  255. if ( !matcher( _c )->matchesCurrent( _c.get() ) ) {
  256. }
  257. else if( !_c->getsetdup(_c->currLoc()) ) {
  258. _gotOne();
  259. }
  260. }
  261. _c->advance();
  262. }
  263. virtual QueryOp *_createChild() const {
  264. CountOp *ret = new CountOp( _ns , BSONObj() );
  265. ret->_count = _count;
  266. ret->_skip = _skip;
  267. ret->_limit = _limit;
  268. return ret;
  269. }
  270. long long count() const { return _count; }
  271. virtual bool mayRecordPlan() const {
  272. return ( _myCount > _limit / 2 ) || ( complete() && !stopRequested() );
  273. }
  274. private:
  275. void _gotOne() {
  276. if ( _skip ) {
  277. _skip--;
  278. return;
  279. }
  280. if ( _limit > 0 && _count >= _limit ) {
  281. setStop();
  282. return;
  283. }
  284. _count++;
  285. _myCount++;
  286. }
  287. string _ns;
  288. bool _capped;
  289. long long _count;
  290. long long _myCount;
  291. long long _skip;
  292. long long _limit;
  293. long long _nscanned;
  294. shared_ptr<Cursor> _c;
  295. BSONObj _query;
  296. BtreeCursor * _bc;
  297. BSONObj _firstMatch;
  298. ClientCursor::CleanupPointer _cc;
  299. ClientCursor::YieldData _yieldData;
  300. };
  301. /* { count: "collectionname"[, query: <query>] }
  302. returns -1 on ns does not exist error.
  303. */
  304. long long runCount( const char *ns, const BSONObj &cmd, string &err ) {
  305. Client::Context cx(ns);
  306. NamespaceDetails *d = nsdetails( ns );
  307. if ( !d ) {
  308. err = "ns missing";
  309. return -1;
  310. }
  311. BSONObj query = cmd.getObjectField("query");
  312. // count of all objects
  313. if ( query.isEmpty() ) {
  314. return applySkipLimit( d->stats.nrecords , cmd );
  315. }
  316. MultiPlanScanner mps( ns, query, BSONObj(), 0, true, BSONObj(), BSONObj(), false, true );
  317. CountOp original( ns , cmd );
  318. shared_ptr< CountOp > res = mps.runOp( original );
  319. if ( !res->complete() ) {
  320. log() << "Count with ns: " << ns << " and query: " << query
  321. << " failed with exception: " << res->exception()
  322. << endl;
  323. return 0;
  324. }
  325. return res->count();
  326. }
  327. class ExplainBuilder {
  328. // Note: by default we filter out allPlans and oldPlan in the shell's
  329. // explain() function. If you add any recursive structures, make sure to
  330. // edit the JS to make sure everything gets filtered.
  331. public:
  332. ExplainBuilder() : _i() {}
  333. void ensureStartScan() {
  334. if ( !_a.get() ) {
  335. _a.reset( new BSONArrayBuilder() );
  336. }
  337. }
  338. void noteCursor( Cursor *c ) {
  339. BSONObjBuilder b( _a->subobjStart() );
  340. b << "cursor" << c->toString() << "indexBounds" << c->prettyIndexBounds();
  341. b.done();
  342. }
  343. void noteScan( Cursor *c, long long nscanned, long long nscannedObjects, int n, bool scanAndOrder,
  344. int millis, bool hint, int nYields , int nChunkSkips , bool indexOnly ) {
  345. if ( _i == 1 ) {
  346. _c.reset( new BSONArrayBuilder() );
  347. *_c << _b->obj();
  348. }
  349. if ( _i == 0 ) {
  350. _b.reset( new BSONObjBuilder() );
  351. }
  352. else {
  353. _b.reset( new BSONObjBuilder( _c->subobjStart() ) );
  354. }
  355. *_b << "cursor" << c->toString();
  356. _b->appendNumber( "nscanned", nscanned );
  357. _b->appendNumber( "nscannedObjects", nscannedObjects );
  358. *_b << "n" << n;
  359. if ( scanAndOrder )
  360. *_b << "scanAndOrder" << true;
  361. *_b << "millis" << millis;
  362. *_b << "nYields" << nYields;
  363. *_b << "nChunkSkips" << nChunkSkips;
  364. *_b << "isMultiKey" << c->isMultiKey();
  365. *_b << "indexOnly" << indexOnly;
  366. *_b << "indexBounds" << c->prettyIndexBounds();
  367. c->explainDetails( *_b );
  368. if ( !hint ) {
  369. *_b << "allPlans" << _a->arr();
  370. }
  371. if ( _i != 0 ) {
  372. _b->done();
  373. }
  374. _a.reset( 0 );
  375. ++_i;
  376. }
  377. BSONObj finishWithSuffix( long long nscanned, long long nscannedObjects, int n, int millis, const BSONObj &suffix ) {
  378. if ( _i > 1 ) {
  379. BSONObjBuilder b;
  380. b << "clauses" << _c->arr();
  381. b.appendNumber( "nscanned", nscanned );
  382. b.appendNumber( "nscannedObjects", nscannedObjects );
  383. b << "n" << n;
  384. b << "millis" << millis;
  385. b.appendElements( suffix );
  386. return b.obj();
  387. }
  388. else {
  389. _b->appendElements( suffix );
  390. return _b->obj();
  391. }
  392. }
  393. private:
  394. auto_ptr< BSONArrayBuilder > _a;
  395. auto_ptr< BSONObjBuilder > _b;
  396. auto_ptr< BSONArrayBuilder > _c;
  397. int _i;
  398. };
  399. // Implements database 'query' requests using the query optimizer's QueryOp interface
  400. class UserQueryOp : public QueryOp {
  401. public:
  402. UserQueryOp( const ParsedQuery& pq, Message &response, ExplainBuilder &eb, CurOp &curop ) :
  403. _buf( 32768 ) , // TODO be smarter here
  404. _pq( pq ) ,
  405. _ntoskip( pq.getSkip() ) ,
  406. _nscanned(0), _oldNscanned(0), _nscannedObjects(0), _oldNscannedObjects(0),
  407. _n(0),
  408. _oldN(0),
  409. _nYields(),
  410. _nChunkSkips(),
  411. _chunkManager( shardingState.needShardChunkManager(pq.ns()) ?
  412. shardingState.getShardChunkManager(pq.ns()) : ShardChunkManagerPtr() ),
  413. _inMemSort(false),
  414. _capped(false),
  415. _saveClientCursor(false),
  416. _wouldSaveClientCursor(false),
  417. _oplogReplay( pq.hasOption( QueryOption_OplogReplay) ),
  418. _response( response ),
  419. _eb( eb ),
  420. _curop( curop )
  421. {}
  422. virtual void _init() {
  423. // only need to put the QueryResult fields there if we're building the first buffer in the message.
  424. if ( _response.empty() ) {
  425. _buf.skip( sizeof( QueryResult ) );
  426. }
  427. if ( _oplogReplay ) {
  428. _findingStartCursor.reset( new FindingStartCursor( qp() ) );
  429. _capped = true;
  430. }
  431. else {
  432. _c = qp().newCursor( DiskLoc() , _pq.getNumToReturn() + _pq.getSkip() );
  433. _capped = _c->capped();
  434. // setup check for if we can only use index to extract
  435. if ( _c->modifiedKeys() == false && _c->isMultiKey() == false && _pq.getFields() ) {
  436. _keyFieldsOnly.reset( _pq.getFields()->checkKey( _c->indexKeyPattern() ) );
  437. }
  438. }
  439. if ( qp().scanAndOrderRequired() ) {
  440. _inMemSort = true;
  441. _so.reset( new ScanAndOrder( _pq.getSkip() , _pq.getNumToReturn() , _pq.getOrder(), qp().multikeyFrs() ) );
  442. }
  443. if ( _pq.isExplain() ) {
  444. _eb.noteCursor( _c.get() );
  445. }
  446. }
  447. virtual bool prepareToYield() {
  448. if ( _findingStartCursor.get() ) {
  449. return _findingStartCursor->prepareToYield();
  450. }
  451. else {
  452. if ( _c && !_cc ) {
  453. _cc.reset( new ClientCursor( QueryOption_NoCursorTimeout , _c , _pq.ns() ) );
  454. }
  455. if ( _cc ) {
  456. return _cc->prepareToYield( _yieldData );
  457. }
  458. }
  459. // no active cursor - ok to yield
  460. return true;
  461. }
  462. virtual void recoverFromYield() {
  463. _nYields++;
  464. if ( _findingStartCursor.get() ) {
  465. _findingStartCursor->recoverFromYield();
  466. }
  467. else if ( _cc && !ClientCursor::recoverFromYield( _yieldData ) ) {
  468. _c.reset();
  469. _cc.reset();
  470. _so.reset();
  471. if ( _capped ) {
  472. msgassertedNoTrace( 13338, str::stream() << "capped cursor overrun during query: " << _pq.ns() );
  473. }
  474. else if ( qp().mustAssertOnYieldFailure() ) {
  475. msgassertedNoTrace( 15890, str::stream() << "UserQueryOp::recoverFromYield() failed to recover: " << _pq.ns() );
  476. }
  477. else {
  478. // we don't fail query since we're fine with returning partial data if collection dropped
  479. // todo: this is wrong. the cursor could be gone if closeAllDatabases command just ran
  480. }
  481. }
  482. }
  483. virtual long long nscanned() {
  484. if ( _findingStartCursor.get() ) {
  485. return 0; // should only be one query plan, so value doesn't really matter.
  486. }
  487. return _c.get() ? _c->nscanned() : _nscanned;
  488. }
  489. virtual void next() {
  490. if ( _findingStartCursor.get() ) {
  491. if ( !_findingStartCursor->done() ) {
  492. _findingStartCursor->next();
  493. }
  494. if ( _findingStartCursor->done() ) {
  495. _c = _findingStartCursor->cursor();
  496. _findingStartCursor.reset( 0 );
  497. }
  498. _capped = true;
  499. return;
  500. }
  501. if ( !_c || !_c->ok() ) {
  502. finish( false );
  503. return;
  504. }
  505. bool mayCreateCursor1 = _pq.wantMore() && ! _inMemSort && _pq.getNumToReturn() != 1 && useCursors;
  506. if( 0 ) {
  507. cout << "SCANNING this: " << this << " key: " << _c->currKey() << " obj: " << _c->current() << endl;
  508. }
  509. if ( _pq.getMaxScan() && _nscanned >= _pq.getMaxScan() ) {
  510. finish( true ); //?
  511. return;
  512. }
  513. _nscanned = _c->nscanned();
  514. if ( !matcher( _c )->matchesCurrent(_c.get() , &_details ) ) {
  515. // not a match, continue onward
  516. if ( _details._loadedObject )
  517. _nscannedObjects++;
  518. }
  519. else {
  520. _nscannedObjects++;
  521. DiskLoc cl = _c->currLoc();
  522. if ( _chunkManager && ! _chunkManager->belongsToMe( cl.obj() ) ) { // TODO: should make this covered at some point
  523. _nChunkSkips++;
  524. // log() << "TEMP skipping un-owned chunk: " << _c->current() << endl;
  525. }
  526. else if( _c->getsetdup(cl) ) {
  527. // dup
  528. }
  529. else {
  530. // got a match.
  531. if ( _inMemSort ) {
  532. // note: no cursors for non-indexed, ordered results. results must be fairly small.
  533. _so->add( _pq.returnKey() ? _c->currKey() : _c->current(), _pq.showDiskLoc() ? &cl : 0 );
  534. }
  535. else if ( _ntoskip > 0 ) {
  536. _ntoskip--;
  537. }
  538. else {
  539. if ( _pq.isExplain() ) {
  540. _n++;
  541. if ( n() >= _pq.getNumToReturn() && !_pq.wantMore() ) {
  542. // .limit() was used, show just that much.
  543. finish( true ); //?
  544. return;
  545. }
  546. }
  547. else {
  548. if ( _pq.returnKey() ) {
  549. BSONObjBuilder bb( _buf );
  550. bb.appendKeys( _c->indexKeyPattern() , _c->currKey() );
  551. bb.done();
  552. }
  553. else if ( _keyFieldsOnly ) {
  554. fillQueryResultFromObj( _buf , 0 , _keyFieldsOnly->hydrate( _c->currKey() ) );
  555. }
  556. else {
  557. BSONObj js = _c->current();
  558. assert( js.isValid() );
  559. if ( _oplogReplay ) {
  560. BSONElement e = js["ts"];
  561. if ( e.type() == Date || e.type() == Timestamp )
  562. _slaveReadTill = e._opTime();
  563. }
  564. fillQueryResultFromObj( _buf , _pq.getFields() , js , (_pq.showDiskLoc() ? &cl : 0));
  565. }
  566. _n++;
  567. if ( ! _c->supportGetMore() ) {
  568. if ( _pq.enough( n() ) || _buf.len() >= MaxBytesToReturnToClientAtOnce ) {
  569. finish( true );
  570. return;
  571. }
  572. }
  573. else if ( _pq.enoughForFirstBatch( n() , _buf.len() ) ) {
  574. /* if only 1 requested, no cursor saved for efficiency...we assume it is findOne() */
  575. if ( mayCreateCursor1 ) {
  576. _wouldSaveClientCursor = true;
  577. if ( _c->advance() ) {
  578. // more...so save a cursor
  579. _saveClientCursor = true;
  580. }
  581. }
  582. finish( true );
  583. return;
  584. }
  585. }
  586. }
  587. }
  588. }
  589. _c->advance();
  590. }
  591. // this plan won, so set data for response broadly
  592. void finish( bool stop ) {
  593. massert( 13638, "client cursor dropped during explain query yield", !_pq.isExplain() || _c.get() );
  594. if ( _pq.isExplain() ) {
  595. _n = _inMemSort ? _so->size() : _n;
  596. }
  597. else if ( _inMemSort ) {
  598. if( _so.get() )
  599. _so->fill( _buf, _pq.getFields() , _n );
  600. }
  601. if ( _c.get() ) {
  602. _nscanned = _c->nscanned();
  603. if ( _pq.hasOption( QueryOption_CursorTailable ) && _pq.getNumToReturn() != 1 )
  604. _c->setTailable();
  605. // If the tailing request succeeded.
  606. if ( _c->tailable() )
  607. _saveClientCursor = true;
  608. }
  609. if ( _pq.isExplain() ) {
  610. _eb.noteScan( _c.get(), _nscanned, _nscannedObjects, _n, scanAndOrderRequired(),
  611. _curop.elapsedMillis(), useHints && !_pq.getHint().eoo(), _nYields ,
  612. _nChunkSkips, _keyFieldsOnly.get() > 0 );
  613. }
  614. else {
  615. if ( _buf.len() ) {
  616. _response.appendData( _buf.buf(), _buf.len() );
  617. _buf.decouple();
  618. }
  619. }
  620. if ( stop ) {
  621. setStop();
  622. }
  623. else {
  624. setComplete();
  625. }
  626. }
  627. void finishExplain( const BSONObj &suffix ) {
  628. BSONObj obj = _eb.finishWithSuffix( totalNscanned(), nscannedObjects(), n(), _curop.elapsedMillis(), suffix);
  629. fillQueryResultFromObj(_buf, 0, obj);
  630. _n = 1;
  631. _oldN = 0;
  632. _response.appendData( _buf.buf(), _buf.len() );
  633. _buf.decouple();
  634. }
  635. virtual bool mayRecordPlan() const {
  636. return ( _pq.getNumToReturn() != 1 ) && ( ( _n > _pq.getNumToReturn() / 2 ) || ( complete() && !stopRequested() ) );
  637. }
  638. virtual QueryOp *_createChild() const {
  639. if ( _pq.isExplain() ) {
  640. _eb.ensureStartScan();
  641. }
  642. UserQueryOp *ret = new UserQueryOp( _pq, _response, _eb, _curop );
  643. ret->_oldN = n();
  644. ret->_oldNscanned = totalNscanned();
  645. ret->_oldNscannedObjects = nscannedObjects();
  646. ret->_ntoskip = _ntoskip;
  647. return ret;
  648. }
  649. bool scanAndOrderRequired() const { return _inMemSort; }
  650. shared_ptr<Cursor> cursor() { return _c; }
  651. int n() const { return _oldN + _n; }
  652. long long totalNscanned() const { return _nscanned + _oldNscanned; }
  653. long long nscannedObjects() const { return _nscannedObjects + _oldNscannedObjects; }
  654. bool saveClientCursor() const { return _saveClientCursor; }
  655. bool wouldSaveClientCursor() const { return _wouldSaveClientCursor; }
  656. void finishForOplogReplay( ClientCursor * cc ) {
  657. if ( _oplogReplay && ! _slaveReadTill.isNull() )
  658. cc->slaveReadTill( _slaveReadTill );
  659. }
  660. ShardChunkManagerPtr getChunkManager(){ return _chunkManager; }
  661. private:
  662. BufBuilder _buf;
  663. const ParsedQuery& _pq;
  664. scoped_ptr<Projection::KeyOnly> _keyFieldsOnly;
  665. long long _ntoskip;
  666. long long _nscanned;
  667. long long _oldNscanned;
  668. long long _nscannedObjects;
  669. long long _oldNscannedObjects;
  670. int _n; // found so far
  671. int _oldN;
  672. int _nYields;
  673. int _nChunkSkips;
  674. MatchDetails _details;
  675. ShardChunkManagerPtr _chunkManager;
  676. bool _inMemSort;
  677. auto_ptr< ScanAndOrder > _so;
  678. shared_ptr<Cursor> _c;
  679. ClientCursor::CleanupPointer _cc;
  680. ClientCursor::YieldData _yieldData;
  681. bool _capped;
  682. bool _saveClientCursor;
  683. bool _wouldSaveClientCursor;
  684. bool _oplogReplay;
  685. auto_ptr< FindingStartCursor > _findingStartCursor;
  686. Message &_response;
  687. ExplainBuilder &_eb;
  688. CurOp &_curop;
  689. OpTime _slaveReadTill;
  690. };
  691. /* run a query -- includes checking for and running a Command \
  692. @return points to ns if exhaust mode. 0=normal mode
  693. */
  694. const char *runQuery(Message& m, QueryMessage& q, CurOp& curop, Message &result) {
  695. shared_ptr<ParsedQuery> pq_shared( new ParsedQuery(q) );
  696. ParsedQuery& pq( *pq_shared );
  697. int ntoskip = q.ntoskip;
  698. BSONObj jsobj = q.query;
  699. int queryOptions = q.queryOptions;
  700. const char *ns = q.ns;
  701. if( logLevel >= 2 )
  702. log() << "runQuery called " << ns << " " << jsobj << endl;
  703. curop.debug().ns = ns;
  704. curop.debug().ntoreturn = pq.getNumToReturn();
  705. curop.setQuery(jsobj);
  706. if ( pq.couldBeCommand() ) {
  707. BufBuilder bb;
  708. bb.skip(sizeof(QueryResult));
  709. BSONObjBuilder cmdResBuf;
  710. if ( runCommands(ns, jsobj, curop, bb, cmdResBuf, false, queryOptions) ) {
  711. curop.debug().iscommand = true;
  712. curop.debug().query = jsobj;
  713. curop.markCommand();
  714. auto_ptr< QueryResult > qr;
  715. qr.reset( (QueryResult *) bb.buf() );
  716. bb.decouple();
  717. qr->setResultFlagsToOk();
  718. qr->len = bb.len();
  719. curop.debug().responseLength = bb.len();
  720. qr->setOperation(opReply);
  721. qr->cursorId = 0;
  722. qr->startingFrom = 0;
  723. qr->nReturned = 1;
  724. result.setData( qr.release(), true );
  725. }
  726. else {
  727. uasserted(13530, "bad or malformed command request?");
  728. }
  729. return 0;
  730. }
  731. /* --- regular query --- */
  732. int n = 0;
  733. BSONElement hint = useHints ? pq.getHint() : BSONElement();
  734. bool explain = pq.isExplain();
  735. bool snapshot = pq.isSnapshot();
  736. BSONObj order = pq.getOrder();
  737. BSONObj query = pq.getFilter();
  738. /* The ElemIter will not be happy if this isn't really an object. So throw exception
  739. here when that is true.
  740. (Which may indicate bad data from client.)
  741. */
  742. if ( query.objsize() == 0 ) {
  743. out() << "Bad query object?\n jsobj:";
  744. out() << jsobj.toString() << "\n query:";
  745. out() << query.toString() << endl;
  746. uassert( 10110 , "bad query object", false);
  747. }
  748. /* --- read lock --- */
  749. mongolock lk(false);
  750. Client::Context ctx( ns , dbpath , &lk );
  751. replVerifyReadsOk(pq);
  752. if ( pq.hasOption( QueryOption_CursorTailable ) ) {
  753. NamespaceDetails *d = nsdetails( ns );
  754. uassert( 13051, "tailable cursor requested on non capped collection", d && d->capped );
  755. const BSONObj nat1 = BSON( "$natural" << 1 );
  756. if ( order.isEmpty() ) {
  757. order = nat1;
  758. }
  759. else {
  760. uassert( 13052, "only {$natural:1} order allowed for tailable cursor", order == nat1 );
  761. }
  762. }
  763. BSONObj snapshotHint; // put here to keep the data in scope
  764. if( snapshot ) {
  765. NamespaceDetails *d = nsdetails(ns);
  766. if ( d ) {
  767. int i = d->findIdIndex();
  768. if( i < 0 ) {
  769. if ( strstr( ns , ".system." ) == 0 )
  770. log() << "warning: no _id index on $snapshot query, ns:" << ns << endl;
  771. }
  772. else {
  773. /* [dm] the name of an _id index tends to vary, so we build the hint the hard way here.
  774. probably need a better way to specify "use the _id index" as a hint. if someone is
  775. in the query optimizer please fix this then!
  776. */
  777. BSONObjBuilder b;
  778. b.append("$hint", d->idx(i).indexName());
  779. snapshotHint = b.obj();
  780. hint = snapshotHint.firstElement();
  781. }
  782. }
  783. }
  784. if ( ! (explain || pq.showDiskLoc()) && isSimpleIdQuery( query ) && !pq.hasOption( QueryOption_CursorTailable ) ) {
  785. bool nsFound = false;
  786. bool indexFound = false;
  787. BSONObj resObject;
  788. Client& c = cc();
  789. bool found = Helpers::findById( c, ns , query , resObject , &nsFound , &indexFound );
  790. if ( nsFound == false || indexFound == true ) {
  791. BufBuilder bb(sizeof(QueryResult)+resObject.objsize()+32);
  792. bb.skip(sizeof(QueryResult));
  793. curop.debug().idhack = true;
  794. if ( found ) {
  795. n = 1;
  796. fillQueryResultFromObj( bb , pq.getFields() , resObject );
  797. }
  798. auto_ptr< QueryResult > qr;
  799. qr.reset( (QueryResult *) bb.buf() );
  800. bb.decouple();
  801. qr->setResultFlagsToOk();
  802. qr->len = bb.len();
  803. curop.debug().responseLength = bb.len();
  804. qr->setOperation(opReply);
  805. qr->cursorId = 0;
  806. qr->startingFrom = 0;
  807. qr->nReturned = n;
  808. result.setData( qr.release(), true );
  809. return NULL;
  810. }
  811. }
  812. // regular, not QO bypass query
  813. BSONObj oldPlan;
  814. if ( explain && ! pq.hasIndexSpecifier() ) {
  815. MultiPlanScanner mps( ns, query, order );
  816. if ( mps.usingPrerecordedPlan() )
  817. oldPlan = mps.oldExplain();
  818. }
  819. auto_ptr< MultiPlanScanner > mps( new MultiPlanScanner( ns, query, order, &hint, !explain, pq.getMin(), pq.getMax(), false, true ) );
  820. BSONObj explainSuffix;
  821. if ( explain ) {
  822. BSONObjBuilder bb;
  823. if ( !oldPlan.isEmpty() )
  824. bb.append( "oldPlan", oldPlan.firstElement().embeddedObject().firstElement().embeddedObject() );
  825. explainSuffix = bb.obj();
  826. }
  827. ExplainBuilder eb;
  828. UserQueryOp original( pq, result, eb, curop );
  829. shared_ptr< UserQueryOp > o = mps->runOp( original );
  830. UserQueryOp &dqo = *o;
  831. if ( ! dqo.complete() )
  832. throw MsgAssertionException( dqo.exception() );
  833. if ( explain ) {
  834. dqo.finishExplain( explainSuffix );
  835. }
  836. n = dqo.n();
  837. long long nscanned = dqo.totalNscanned();
  838. curop.debug().scanAndOrder = dqo.scanAndOrderRequired();
  839. shared_ptr<Cursor> cursor = dqo.cursor();
  840. if( logLevel >= 5 )
  841. log() << " used cursor: " << cursor.get() << endl;
  842. long long cursorid = 0;
  843. const char * exhaust = 0;
  844. if ( dqo.saveClientCursor() || ( dqo.wouldSaveClientCursor() && mps->mayRunMore() ) ) {
  845. ClientCursor *cc;
  846. bool moreClauses = mps->mayRunMore();
  847. if ( moreClauses ) {
  848. // this MultiCursor will use a dumb NoOp to advance(), so no need to specify mayYield
  849. shared_ptr< Cursor > multi( new MultiCursor( mps, cursor, dqo.matcher( cursor ), dqo ) );
  850. cc = new ClientCursor(queryOptions, multi, ns, jsobj.getOwned());
  851. }
  852. else {
  853. if( ! cursor->matcher() ) cursor->setMatcher( dqo.matcher( cursor ) );
  854. cc = new ClientCursor( queryOptions, cursor, ns, jsobj.getOwned() );
  855. }
  856. cc->setChunkManager( dqo.getChunkManager() );
  857. cursorid = cc->cursorid();
  858. DEV tlog(2) << "query has more, cursorid: " << cursorid << endl;
  859. cc->setPos( n );
  860. cc->pq = pq_shared;
  861. cc->fields = pq.getFieldPtr();
  862. cc->originalMessage = m;
  863. cc->updateLocation();
  864. if ( !cc->ok() && cc->c()->tailable() )
  865. DEV tlog() << "query has no more but tailable, cursorid: " << cursorid << endl;
  866. if( queryOptions & QueryOption_Exhaust ) {
  867. exhaust = ns;
  868. curop.debug().exhaust = true;
  869. }
  870. dqo.finishForOplogReplay(cc);
  871. }
  872. QueryResult *qr = (QueryResult *) result.header();
  873. qr->cursorId = cursorid;
  874. qr->setResultFlagsToOk();
  875. // qr->len is updated automatically by appendData()
  876. curop.debug().responseLength = qr->len;
  877. qr->setOperation(opReply);
  878. qr->startingFrom = 0;
  879. qr->nReturned = n;
  880. int duration = curop.elapsedMillis();
  881. bool dbprofile = curop.shouldDBProfile( duration );
  882. if ( dbprofile || duration >= cmdLine.slowMS ) {
  883. curop.debug().nscanned = (int) nscanned;
  884. curop.debug().ntoskip = ntoskip;
  885. }
  886. curop.debug().nreturned = n;
  887. return exhaust;
  888. }
  889. } // namespace mongo