diff options
author | Henrik Edin <henrik.edin@mongodb.com> | 2020-08-14 10:23:04 -0400 |
---|---|---|
committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2020-09-02 23:53:39 +0000 |
commit | bf5914a20b596ba3bde772b42e579e028f733bac (patch) | |
tree | 2b26469571786d9adb5e95c47990c2416bfab9c4 /src | |
parent | 6b3e341703b781bb1ff7b1263406a0f1d28dd77c (diff) | |
download | mongo-bf5914a20b596ba3bde772b42e579e028f733bac.tar.gz |
SERVER-50317 Const correct uses of Collection
Most of the code should only need a const Collection now. AutoGetCollection returns a const Collection by default. There is a placeholder getWritableCollection() interface that will handle the necessary steps we need for lock free reads in the future.
Added some operators to AutoGetCollection so it behaves more like a smart pointer.
Diffstat (limited to 'src')
159 files changed, 790 insertions, 724 deletions
diff --git a/src/mongo/db/auth/auth_op_observer.cpp b/src/mongo/db/auth/auth_op_observer.cpp index df5695e2a0a..4e10e8d2d21 100644 --- a/src/mongo/db/auth/auth_op_observer.cpp +++ b/src/mongo/db/auth/auth_op_observer.cpp @@ -90,7 +90,7 @@ void AuthOpObserver::onDelete(OperationContext* opCtx, } void AuthOpObserver::onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/auth/auth_op_observer.h b/src/mongo/db/auth/auth_op_observer.h index 2dc13af3bd8..b8d0e132b7a 100644 --- a/src/mongo/db/auth/auth_op_observer.h +++ b/src/mongo/db/auth/auth_op_observer.h @@ -106,7 +106,7 @@ public: const boost::optional<OplogSlot> slot) final{}; void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/catalog/capped_utils.cpp b/src/mongo/db/catalog/capped_utils.cpp index bc5b78af2f1..5dd3533fc91 100644 --- a/src/mongo/db/catalog/capped_utils.cpp +++ b/src/mongo/db/catalog/capped_utils.cpp @@ -72,7 +72,8 @@ Status emptyCapped(OperationContext* opCtx, const NamespaceString& collectionNam uassert(ErrorCodes::NamespaceNotFound, "no such database", db); Collection* collection = - CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, collectionName); + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, + collectionName); uassert(ErrorCodes::CommandNotSupportedOnView, str::stream() << "emptycapped not supported on view: " << collectionName.ns(), collection || !ViewCatalog::get(db)->lookup(opCtx, collectionName.ns())); @@ -114,7 +115,7 @@ void cloneCollectionAsCapped(OperationContext* opCtx, const NamespaceString& toNss, long long size, bool temp) { - Collection* fromCollection = + const Collection* fromCollection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, fromNss); if (!fromCollection) { uassert(ErrorCodes::CommandNotSupportedOnView, @@ -153,7 +154,7 @@ void cloneCollectionAsCapped(OperationContext* opCtx, uassertStatusOK(createCollection(opCtx, toNss.db().toString(), cmd.done())); } - Collection* toCollection = + const Collection* toCollection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, toNss); invariant(toCollection); // we created above @@ -243,7 +244,7 @@ void convertToCapped(OperationContext* opCtx, const NamespaceString& ns, long lo StringData dbname = ns.db(); StringData shortSource = ns.coll(); - AutoGetCollection autoColl(opCtx, ns, MODE_X); + AutoGetCollection coll(opCtx, ns, MODE_X); bool userInitiatedWritesAndNotPrimary = opCtx->writesAreReplicated() && !repl::ReplicationCoordinator::get(opCtx)->canAcceptWritesFor(opCtx, ns); @@ -252,11 +253,11 @@ void convertToCapped(OperationContext* opCtx, const NamespaceString& ns, long lo str::stream() << "Not primary while converting " << ns << " to a capped collection", !userInitiatedWritesAndNotPrimary); - Database* const db = autoColl.getDb(); + Database* const db = coll.getDb(); uassert( ErrorCodes::NamespaceNotFound, str::stream() << "database " << dbname << " not found", db); - if (Collection* coll = autoColl.getCollection()) { + if (coll) { IndexBuildsCoordinator::get(opCtx)->assertNoIndexBuildInProgForCollection(coll->uuid()); } diff --git a/src/mongo/db/catalog/catalog_control.cpp b/src/mongo/db/catalog/catalog_control.cpp index 4d433798cb1..e12b489f558 100644 --- a/src/mongo/db/catalog/catalog_control.cpp +++ b/src/mongo/db/catalog/catalog_control.cpp @@ -190,7 +190,8 @@ void openCatalog(OperationContext* opCtx, const MinVisibleTimestampMap& minVisib CollectionCatalog::get(opCtx).getAllCollectionNamesFromDb(opCtx, dbName)) { // Note that the collection name already includes the database component. auto collection = - CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, collNss); + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, + collNss); invariant(collection, str::stream() << "failed to get valid collection pointer for namespace " << collNss); diff --git a/src/mongo/db/catalog/coll_mod.cpp b/src/mongo/db/catalog/coll_mod.cpp index c8010e21b6b..8a75e773a89 100644 --- a/src/mongo/db/catalog/coll_mod.cpp +++ b/src/mongo/db/catalog/coll_mod.cpp @@ -112,7 +112,7 @@ struct CollModRequest { StatusWith<CollModRequest> parseCollModRequest(OperationContext* opCtx, const NamespaceString& nss, - Collection* coll, + const Collection* coll, const BSONObj& cmdObj, BSONObjBuilder* oplogEntryBuilder) { @@ -346,12 +346,11 @@ Status _collModInternal(OperationContext* opCtx, const BSONObj& cmdObj, BSONObjBuilder* result) { StringData dbName = nss.db(); - AutoGetCollection autoColl(opCtx, nss, MODE_X, AutoGetCollectionViewMode::kViewsPermitted); + AutoGetCollection coll(opCtx, nss, MODE_X, AutoGetCollectionViewMode::kViewsPermitted); Lock::CollectionLock systemViewsLock( opCtx, NamespaceString(dbName, NamespaceString::kSystemDotViewsCollectionName), MODE_X); - Database* const db = autoColl.getDb(); - Collection* coll = autoColl.getCollection(); + Database* const db = coll.getDb(); CurOpFailpointHelpers::waitWhileFailPointEnabled( &hangAfterDatabaseLock, opCtx, "hangAfterDatabaseLock", []() {}, false, nss); @@ -391,7 +390,8 @@ Status _collModInternal(OperationContext* opCtx, } BSONObjBuilder oplogEntryBuilder; - auto statusW = parseCollModRequest(opCtx, nss, coll, cmdObj, &oplogEntryBuilder); + auto statusW = + parseCollModRequest(opCtx, nss, coll.getCollection(), cmdObj, &oplogEntryBuilder); if (!statusW.isOK()) { return statusW.getStatus(); } @@ -498,7 +498,7 @@ Status _collModInternal(OperationContext* opCtx, // Notify the index catalog that the definition of this index changed. This will // invalidate the local idx pointer. On rollback of this WUOW, the idx pointer in // cmrNew will be invalidated and the local var idx pointer will be valid again. - cmrNew.idx = coll->getIndexCatalog()->refreshEntry(opCtx, idx); + cmrNew.idx = coll.getWritableCollection()->getIndexCatalog()->refreshEntry(opCtx, idx); opCtx->recoveryUnit()->registerChange(std::make_unique<CollModResultChange>( oldExpireSecs, newExpireSecs, oldHidden, newHidden, result)); @@ -509,19 +509,20 @@ Status _collModInternal(OperationContext* opCtx, } if (cmrNew.collValidator) { - coll->setValidator(opCtx, std::move(*cmrNew.collValidator)); + coll.getWritableCollection()->setValidator(opCtx, std::move(*cmrNew.collValidator)); } if (cmrNew.collValidationAction) - uassertStatusOKWithContext( - coll->setValidationAction(opCtx, *cmrNew.collValidationAction), - "Failed to set validationAction"); + uassertStatusOKWithContext(coll.getWritableCollection()->setValidationAction( + opCtx, *cmrNew.collValidationAction), + "Failed to set validationAction"); if (cmrNew.collValidationLevel) { - uassertStatusOKWithContext(coll->setValidationLevel(opCtx, *cmrNew.collValidationLevel), + uassertStatusOKWithContext(coll.getWritableCollection()->setValidationLevel( + opCtx, *cmrNew.collValidationLevel), "Failed to set validationLevel"); } if (cmrNew.recordPreImages != oldCollOptions.recordPreImages) { - coll->setRecordPreImages(opCtx, cmrNew.recordPreImages); + coll.getWritableCollection()->setRecordPreImages(opCtx, cmrNew.recordPreImages); } // Only observe non-view collMods, as view operations are observed as operations on the diff --git a/src/mongo/db/catalog/collection.h b/src/mongo/db/catalog/collection.h index dc3375429ad..9914a63f76c 100644 --- a/src/mongo/db/catalog/collection.h +++ b/src/mongo/db/catalog/collection.h @@ -294,8 +294,7 @@ public: virtual const IndexCatalog* getIndexCatalog() const = 0; virtual IndexCatalog* getIndexCatalog() = 0; - virtual const RecordStore* getRecordStore() const = 0; - virtual RecordStore* getRecordStore() = 0; + virtual RecordStore* getRecordStore() const = 0; /** * Fetches the Ident for this collection. @@ -336,7 +335,7 @@ public: OpDebug* const opDebug, const bool fromMigrate = false, const bool noWarn = false, - StoreDeletedDoc storeDeletedDoc = StoreDeletedDoc::Off) = 0; + StoreDeletedDoc storeDeletedDoc = StoreDeletedDoc::Off) const = 0; /* * Inserts all documents inside one WUOW. @@ -349,7 +348,7 @@ public: const std::vector<InsertStatement>::const_iterator begin, const std::vector<InsertStatement>::const_iterator end, OpDebug* const opDebug, - const bool fromMigrate = false) = 0; + const bool fromMigrate = false) const = 0; /** * this does NOT modify the doc before inserting @@ -360,7 +359,7 @@ public: virtual Status insertDocument(OperationContext* const opCtx, const InsertStatement& doc, OpDebug* const opDebug, - const bool fromMigrate = false) = 0; + const bool fromMigrate = false) const = 0; /** * Callers must ensure no document validation is performed for this collection when calling @@ -368,7 +367,7 @@ public: */ virtual Status insertDocumentsForOplog(OperationContext* const opCtx, std::vector<Record>* records, - const std::vector<Timestamp>& timestamps) = 0; + const std::vector<Timestamp>& timestamps) const = 0; /** * Inserts a document into the record store for a bulk loader that manages the index building @@ -377,9 +376,10 @@ public: * * NOTE: It is up to caller to commit the indexes. */ - virtual Status insertDocumentForBulkLoader(OperationContext* const opCtx, - const BSONObj& doc, - const OnRecordInsertedFn& onRecordInserted) = 0; + virtual Status insertDocumentForBulkLoader( + OperationContext* const opCtx, + const BSONObj& doc, + const OnRecordInsertedFn& onRecordInserted) const = 0; /** * Updates the document @ oldLocation with newDoc. @@ -396,7 +396,7 @@ public: const BSONObj& newDoc, const bool indexesAffected, OpDebug* const opDebug, - CollectionUpdateArgs* const args) = 0; + CollectionUpdateArgs* const args) const = 0; virtual bool updateWithDamagesSupported() const = 0; @@ -413,7 +413,7 @@ public: const Snapshotted<RecordData>& oldRec, const char* const damageSource, const mutablebson::DamageVector& damages, - CollectionUpdateArgs* const args) = 0; + CollectionUpdateArgs* const args) const = 0; // ----------- diff --git a/src/mongo/db/catalog/collection_catalog.cpp b/src/mongo/db/catalog/collection_catalog.cpp index 3ffb309d55a..8457f524beb 100644 --- a/src/mongo/db/catalog/collection_catalog.cpp +++ b/src/mongo/db/catalog/collection_catalog.cpp @@ -268,8 +268,13 @@ std::shared_ptr<const Collection> CollectionCatalog::lookupCollectionByUUIDForRe return (coll && coll->isCommitted()) ? coll : nullptr; } -Collection* CollectionCatalog::lookupCollectionByUUID(OperationContext* opCtx, - CollectionUUID uuid) const { +Collection* CollectionCatalog::lookupCollectionByUUIDForMetadataWrite(OperationContext* opCtx, + CollectionUUID uuid) { + return const_cast<Collection*>(lookupCollectionByUUID(opCtx, uuid)); +} + +const Collection* CollectionCatalog::lookupCollectionByUUID(OperationContext* opCtx, + CollectionUUID uuid) const { if (auto coll = UncommittedCollections::getForTxn(opCtx, uuid)) { return coll.get(); } @@ -309,8 +314,13 @@ std::shared_ptr<const Collection> CollectionCatalog::lookupCollectionByNamespace return (coll && coll->isCommitted()) ? coll : nullptr; } -Collection* CollectionCatalog::lookupCollectionByNamespace(OperationContext* opCtx, - const NamespaceString& nss) const { +Collection* CollectionCatalog::lookupCollectionByNamespaceForMetadataWrite( + OperationContext* opCtx, const NamespaceString& nss) { + return const_cast<Collection*>(lookupCollectionByNamespace(opCtx, nss)); +} + +const Collection* CollectionCatalog::lookupCollectionByNamespace(OperationContext* opCtx, + const NamespaceString& nss) const { if (auto coll = UncommittedCollections::getForTxn(opCtx, nss)) { return coll.get(); } diff --git a/src/mongo/db/catalog/collection_catalog.h b/src/mongo/db/catalog/collection_catalog.h index 5ee50d0b745..c63a960661c 100644 --- a/src/mongo/db/catalog/collection_catalog.h +++ b/src/mongo/db/catalog/collection_catalog.h @@ -142,7 +142,9 @@ public: * * Returns nullptr if the 'uuid' is not known. */ - Collection* lookupCollectionByUUID(OperationContext* opCtx, CollectionUUID uuid) const; + Collection* lookupCollectionByUUIDForMetadataWrite(OperationContext* opCtx, + CollectionUUID uuid); + const Collection* lookupCollectionByUUID(OperationContext* opCtx, CollectionUUID uuid) const; std::shared_ptr<const Collection> lookupCollectionByUUIDForRead(OperationContext* opCtx, CollectionUUID uuid) const; @@ -162,8 +164,10 @@ public: * * Returns nullptr if the namespace is unknown. */ - Collection* lookupCollectionByNamespace(OperationContext* opCtx, - const NamespaceString& nss) const; + Collection* lookupCollectionByNamespaceForMetadataWrite(OperationContext* opCtx, + const NamespaceString& nss); + const Collection* lookupCollectionByNamespace(OperationContext* opCtx, + const NamespaceString& nss) const; std::shared_ptr<const Collection> lookupCollectionByNamespaceForRead( OperationContext* opCtx, const NamespaceString& nss) const; diff --git a/src/mongo/db/catalog/collection_catalog_helper.cpp b/src/mongo/db/catalog/collection_catalog_helper.cpp index d867ed33ea1..069bc1558f0 100644 --- a/src/mongo/db/catalog/collection_catalog_helper.cpp +++ b/src/mongo/db/catalog/collection_catalog_helper.cpp @@ -52,7 +52,7 @@ void forEachCollectionFromDb(OperationContext* opCtx, } boost::optional<Lock::CollectionLock> clk; - Collection* collection = nullptr; + const Collection* collection = nullptr; while (auto nss = catalog.lookupNSSByUUID(opCtx, uuid)) { // Get a fresh snapshot for each locked collection to see any catalog changes. diff --git a/src/mongo/db/catalog/collection_catalog_test.cpp b/src/mongo/db/catalog/collection_catalog_test.cpp index 9781eb640df..94b2156927d 100644 --- a/src/mongo/db/catalog/collection_catalog_test.cpp +++ b/src/mongo/db/catalog/collection_catalog_test.cpp @@ -45,7 +45,7 @@ namespace mongo { namespace { /** - * A test fixture that creates a CollectionCatalog and Collection* pointer to store in it. + * A test fixture that creates a CollectionCatalog and const Collection* pointer to store in it. */ class CollectionCatalogTest : public ServiceContextMongoDTest { public: @@ -78,7 +78,7 @@ protected: CollectionCatalog catalog; OperationContextNoop opCtx; NamespaceString nss; - Collection* col; + const Collection* col; CollectionUUID colUUID; CollectionUUID nextUUID; CollectionUUID prevUUID; @@ -112,13 +112,13 @@ public: } } - std::map<CollectionUUID, Collection*>::iterator collsIterator(std::string dbName) { + std::map<CollectionUUID, const Collection*>::iterator collsIterator(std::string dbName) { auto it = dbMap.find(dbName); ASSERT(it != dbMap.end()); return it->second.begin(); } - std::map<CollectionUUID, Collection*>::iterator collsIteratorEnd(std::string dbName) { + std::map<CollectionUUID, const Collection*>::iterator collsIteratorEnd(std::string dbName) { auto it = dbMap.find(dbName); ASSERT(it != dbMap.end()); return it->second.end(); @@ -148,7 +148,7 @@ public: protected: CollectionCatalog catalog; OperationContextNoop opCtx; - std::map<std::string, std::map<CollectionUUID, Collection*>> dbMap; + std::map<std::string, std::map<CollectionUUID, const Collection*>> dbMap; }; class CollectionCatalogResourceMapTest : public unittest::Test { @@ -652,7 +652,7 @@ TEST_F(CollectionCatalogTest, GetAllCollectionNamesAndGetAllDbNamesWithUncommitt } // One dbName with only an invisible collection does not appear in dbNames. - auto invisibleCollA = catalog.lookupCollectionByNamespace(&opCtx, aColl); + auto invisibleCollA = catalog.lookupCollectionByNamespaceForMetadataWrite(&opCtx, aColl); invisibleCollA->setCommitted(false); auto res = catalog.getAllCollectionNamesFromDb(&opCtx, "dbA"); @@ -669,7 +669,7 @@ TEST_F(CollectionCatalogTest, GetAllCollectionNamesAndGetAllDbNamesWithUncommitt std::vector<NamespaceString> dCollList = dbDNss; dCollList.erase(std::find(dCollList.begin(), dCollList.end(), nss)); - auto invisibleCollD = catalog.lookupCollectionByNamespace(&opCtx, nss); + auto invisibleCollD = catalog.lookupCollectionByNamespaceForMetadataWrite(&opCtx, nss); invisibleCollD->setCommitted(false); res = catalog.getAllCollectionNamesFromDb(&opCtx, "dbD"); @@ -684,7 +684,7 @@ TEST_F(CollectionCatalogTest, GetAllCollectionNamesAndGetAllDbNamesWithUncommitt // If all dbNames consist only of invisible collections, none of these dbs is visible. for (auto& nss : nsss) { - auto invisibleColl = catalog.lookupCollectionByNamespace(&opCtx, nss); + auto invisibleColl = catalog.lookupCollectionByNamespaceForMetadataWrite(&opCtx, nss); invisibleColl->setCommitted(false); } diff --git a/src/mongo/db/catalog/collection_compact.cpp b/src/mongo/db/catalog/collection_compact.cpp index 19e31d14568..f143dd89d1d 100644 --- a/src/mongo/db/catalog/collection_compact.cpp +++ b/src/mongo/db/catalog/collection_compact.cpp @@ -50,13 +50,14 @@ using logv2::LogComponent; namespace { -Collection* getCollectionForCompact(OperationContext* opCtx, - Database* database, - const NamespaceString& collectionNss) { +const Collection* getCollectionForCompact(OperationContext* opCtx, + Database* database, + const NamespaceString& collectionNss) { invariant(opCtx->lockState()->isCollectionLockedForMode(collectionNss, MODE_IX)); CollectionCatalog& collectionCatalog = CollectionCatalog::get(opCtx); - Collection* collection = collectionCatalog.lookupCollectionByNamespace(opCtx, collectionNss); + const Collection* collection = + collectionCatalog.lookupCollectionByNamespace(opCtx, collectionNss); if (!collection) { std::shared_ptr<ViewDefinition> view = @@ -81,7 +82,7 @@ StatusWith<int64_t> compactCollection(OperationContext* opCtx, boost::optional<Lock::CollectionLock> collLk; collLk.emplace(opCtx, collectionNss, MODE_X); - Collection* collection = getCollectionForCompact(opCtx, database, collectionNss); + const Collection* collection = getCollectionForCompact(opCtx, database, collectionNss); DisableDocumentValidation validationDisabler(opCtx); auto recordStore = collection->getRecordStore(); diff --git a/src/mongo/db/catalog/collection_impl.cpp b/src/mongo/db/catalog/collection_impl.cpp index c113ce8e34c..f30be055410 100644 --- a/src/mongo/db/catalog/collection_impl.cpp +++ b/src/mongo/db/catalog/collection_impl.cpp @@ -483,7 +483,7 @@ Collection::Validator CollectionImpl::parseValidator( Status CollectionImpl::insertDocumentsForOplog(OperationContext* opCtx, std::vector<Record>* records, - const std::vector<Timestamp>& timestamps) { + const std::vector<Timestamp>& timestamps) const { dassert(opCtx->lockState()->isWriteLocked()); // Since this is only for the OpLog, we can assume these for simplicity. @@ -506,7 +506,7 @@ Status CollectionImpl::insertDocuments(OperationContext* opCtx, const std::vector<InsertStatement>::const_iterator begin, const std::vector<InsertStatement>::const_iterator end, OpDebug* opDebug, - bool fromMigrate) { + bool fromMigrate) const { auto status = checkFailCollectionInsertsFailPoint(_ns, (begin != end ? begin->doc : BSONObj())); if (!status.isOK()) { @@ -574,15 +574,14 @@ Status CollectionImpl::insertDocuments(OperationContext* opCtx, Status CollectionImpl::insertDocument(OperationContext* opCtx, const InsertStatement& docToInsert, OpDebug* opDebug, - bool fromMigrate) { + bool fromMigrate) const { std::vector<InsertStatement> docs; docs.push_back(docToInsert); return insertDocuments(opCtx, docs.begin(), docs.end(), opDebug, fromMigrate); } -Status CollectionImpl::insertDocumentForBulkLoader(OperationContext* opCtx, - const BSONObj& doc, - const OnRecordInsertedFn& onRecordInserted) { +Status CollectionImpl::insertDocumentForBulkLoader( + OperationContext* opCtx, const BSONObj& doc, const OnRecordInsertedFn& onRecordInserted) const { auto status = checkFailCollectionInsertsFailPoint(_ns, doc); if (!status.isOK()) { @@ -636,7 +635,7 @@ Status CollectionImpl::insertDocumentForBulkLoader(OperationContext* opCtx, Status CollectionImpl::_insertDocuments(OperationContext* opCtx, const std::vector<InsertStatement>::const_iterator begin, const std::vector<InsertStatement>::const_iterator end, - OpDebug* opDebug) { + OpDebug* opDebug) const { dassert(opCtx->lockState()->isCollectionLockedForMode(ns(), MODE_IX)); const size_t count = std::distance(begin, end); @@ -740,7 +739,7 @@ void CollectionImpl::deleteDocument(OperationContext* opCtx, OpDebug* opDebug, bool fromMigrate, bool noWarn, - Collection::StoreDeletedDoc storeDeletedDoc) { + Collection::StoreDeletedDoc storeDeletedDoc) const { if (isCapped()) { LOGV2(20291, "failing remove on a capped ns {ns}", @@ -780,7 +779,7 @@ RecordId CollectionImpl::updateDocument(OperationContext* opCtx, const BSONObj& newDoc, bool indexesAffected, OpDebug* opDebug, - CollectionUpdateArgs* args) { + CollectionUpdateArgs* args) const { { auto status = checkValidation(opCtx, newDoc); if (!status.isOK()) { @@ -873,7 +872,7 @@ StatusWith<RecordData> CollectionImpl::updateDocumentWithDamages( const Snapshotted<RecordData>& oldRec, const char* damageSource, const mutablebson::DamageVector& damages, - CollectionUpdateArgs* args) { + CollectionUpdateArgs* args) const { dassert(opCtx->lockState()->isCollectionLockedForMode(ns(), MODE_IX)); invariant(oldRec.snapshotId() == opCtx->recoveryUnit()->getSnapshotId()); invariant(updateWithDamagesSupported()); diff --git a/src/mongo/db/catalog/collection_impl.h b/src/mongo/db/catalog/collection_impl.h index 374306ce514..41ed1815a90 100644 --- a/src/mongo/db/catalog/collection_impl.h +++ b/src/mongo/db/catalog/collection_impl.h @@ -88,11 +88,7 @@ public: return _indexCatalog.get(); } - const RecordStore* getRecordStore() const final { - return _recordStore.get(); - } - - RecordStore* getRecordStore() final { + RecordStore* getRecordStore() const final { return _recordStore.get(); } @@ -142,7 +138,7 @@ public: OpDebug* opDebug, bool fromMigrate = false, bool noWarn = false, - Collection::StoreDeletedDoc storeDeletedDoc = Collection::StoreDeletedDoc::Off) final; + Collection::StoreDeletedDoc storeDeletedDoc = Collection::StoreDeletedDoc::Off) const final; /* * Inserts all documents inside one WUOW. @@ -155,7 +151,7 @@ public: std::vector<InsertStatement>::const_iterator begin, std::vector<InsertStatement>::const_iterator end, OpDebug* opDebug, - bool fromMigrate = false) final; + bool fromMigrate = false) const final; /** * this does NOT modify the doc before inserting @@ -166,7 +162,7 @@ public: Status insertDocument(OperationContext* opCtx, const InsertStatement& doc, OpDebug* opDebug, - bool fromMigrate = false) final; + bool fromMigrate = false) const final; /** * Callers must ensure no document validation is performed for this collection when calling @@ -174,7 +170,7 @@ public: */ Status insertDocumentsForOplog(OperationContext* opCtx, std::vector<Record>* records, - const std::vector<Timestamp>& timestamps) final; + const std::vector<Timestamp>& timestamps) const final; /** * Inserts a document into the record store for a bulk loader that manages the index building @@ -185,7 +181,7 @@ public: */ Status insertDocumentForBulkLoader(OperationContext* opCtx, const BSONObj& doc, - const OnRecordInsertedFn& onRecordInserted) final; + const OnRecordInsertedFn& onRecordInserted) const final; /** * Updates the document @ oldLocation with newDoc. @@ -202,7 +198,7 @@ public: const BSONObj& newDoc, bool indexesAffected, OpDebug* opDebug, - CollectionUpdateArgs* args) final; + CollectionUpdateArgs* args) const final; bool updateWithDamagesSupported() const final; @@ -218,7 +214,7 @@ public: const Snapshotted<RecordData>& oldRec, const char* damageSource, const mutablebson::DamageVector& damages, - CollectionUpdateArgs* args) final; + CollectionUpdateArgs* args) const final; // ----------- @@ -383,7 +379,7 @@ private: Status _insertDocuments(OperationContext* opCtx, std::vector<InsertStatement>::const_iterator begin, std::vector<InsertStatement>::const_iterator end, - OpDebug* opDebug); + OpDebug* opDebug) const; // This object is decorable and decorated with unversioned data related to the collection. Not // associated with any particular Collection instance for the collection, but shared across all diff --git a/src/mongo/db/catalog/collection_mock.h b/src/mongo/db/catalog/collection_mock.h index 1466108d5ff..0362503e236 100644 --- a/src/mongo/db/catalog/collection_mock.h +++ b/src/mongo/db/catalog/collection_mock.h @@ -79,10 +79,7 @@ public: return _indexCatalog.get(); } - const RecordStore* getRecordStore() const { - std::abort(); - } - RecordStore* getRecordStore() { + RecordStore* getRecordStore() const { std::abort(); } std::shared_ptr<Ident> getSharedIdent() const { @@ -115,7 +112,7 @@ public: OpDebug* opDebug, bool fromMigrate, bool noWarn, - Collection::StoreDeletedDoc storeDeletedDoc) { + Collection::StoreDeletedDoc storeDeletedDoc) const { std::abort(); } @@ -123,26 +120,26 @@ public: std::vector<InsertStatement>::const_iterator begin, std::vector<InsertStatement>::const_iterator end, OpDebug* opDebug, - bool fromMigrate) { + bool fromMigrate) const { std::abort(); } Status insertDocument(OperationContext* opCtx, const InsertStatement& doc, OpDebug* opDebug, - bool fromMigrate) { + bool fromMigrate) const { std::abort(); } Status insertDocumentsForOplog(OperationContext* opCtx, std::vector<Record>* records, - const std::vector<Timestamp>& timestamps) { + const std::vector<Timestamp>& timestamps) const { std::abort(); } Status insertDocumentForBulkLoader(OperationContext* opCtx, const BSONObj& doc, - const OnRecordInsertedFn& onRecordInserted) { + const OnRecordInsertedFn& onRecordInserted) const { std::abort(); } @@ -152,7 +149,7 @@ public: const BSONObj& newDoc, bool indexesAffected, OpDebug* opDebug, - CollectionUpdateArgs* args) { + CollectionUpdateArgs* args) const { std::abort(); } @@ -165,7 +162,7 @@ public: const Snapshotted<RecordData>& oldRec, const char* damageSource, const mutablebson::DamageVector& damages, - CollectionUpdateArgs* args) { + CollectionUpdateArgs* args) const { std::abort(); } diff --git a/src/mongo/db/catalog/collection_validation.cpp b/src/mongo/db/catalog/collection_validation.cpp index 5b1ac9f0fdf..9e24374542a 100644 --- a/src/mongo/db/catalog/collection_validation.cpp +++ b/src/mongo/db/catalog/collection_validation.cpp @@ -353,7 +353,7 @@ std::string multikeyPathsToString(MultikeyPaths paths) { void _validateCatalogEntry(OperationContext* opCtx, ValidateState* validateState, ValidateResults* results) { - Collection* collection = validateState->getCollection(); + const Collection* collection = validateState->getCollection(); CollectionOptions options = DurableCatalog::get(opCtx)->getCollectionOptions(opCtx, collection->getCatalogId()); if (options.uuid) { diff --git a/src/mongo/db/catalog/collection_validation_test.cpp b/src/mongo/db/catalog/collection_validation_test.cpp index 90e548bb9eb..63dcc0d415a 100644 --- a/src/mongo/db/catalog/collection_validation_test.cpp +++ b/src/mongo/db/catalog/collection_validation_test.cpp @@ -164,7 +164,7 @@ int insertDataRange(OperationContext* opCtx, int startIDNum, int endIDNum) { AutoGetCollection autoColl(opCtx, kNss, MODE_IX); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); std::vector<InsertStatement> inserts; for (int i = startIDNum; i < endIDNum; ++i) { auto doc = BSON("_id" << i); @@ -184,7 +184,7 @@ int insertDataRange(OperationContext* opCtx, int startIDNum, int endIDNum) { */ int setUpInvalidData(OperationContext* opCtx) { AutoGetCollection autoColl(opCtx, kNss, MODE_IX); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); RecordStore* rs = coll->getRecordStore(); { diff --git a/src/mongo/db/catalog/create_collection.cpp b/src/mongo/db/catalog/create_collection.cpp index 9aa5e9ccb84..43303c64a1e 100644 --- a/src/mongo/db/catalog/create_collection.cpp +++ b/src/mongo/db/catalog/create_collection.cpp @@ -76,7 +76,7 @@ Status _createView(OperationContext* opCtx, // Create 'system.views' in a separate WUOW if it does not exist. WriteUnitOfWork wuow(opCtx); - Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( + const Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( opCtx, NamespaceString(db->getSystemViewsName())); if (!coll) { coll = db->createCollection(opCtx, NamespaceString(db->getSystemViewsName())); diff --git a/src/mongo/db/catalog/create_collection_test.cpp b/src/mongo/db/catalog/create_collection_test.cpp index cef79c84a45..7f16293665f 100644 --- a/src/mongo/db/catalog/create_collection_test.cpp +++ b/src/mongo/db/catalog/create_collection_test.cpp @@ -284,8 +284,7 @@ TEST_F(CreateCollectionTest, ValidationDisabledForTemporaryReshardingCollection) ASSERT_OK(createCollection(opCtx.get(), reshardingNss.db().toString(), createCmdObj)); ASSERT_TRUE(collectionExists(opCtx.get(), reshardingNss)); - AutoGetCollection agc(opCtx.get(), reshardingNss, MODE_X); - Collection* collection = agc.getCollection(); + AutoGetCollection collection(opCtx.get(), reshardingNss, MODE_X); WriteUnitOfWork wuow(opCtx.get()); // Ensure a document that violates validator criteria can be inserted into the temporary diff --git a/src/mongo/db/catalog/database_impl.cpp b/src/mongo/db/catalog/database_impl.cpp index 3315c56e9d2..beec4fb751a 100644 --- a/src/mongo/db/catalog/database_impl.cpp +++ b/src/mongo/db/catalog/database_impl.cpp @@ -172,7 +172,7 @@ void DatabaseImpl::init(OperationContext* const opCtx) const { auto& catalog = CollectionCatalog::get(opCtx); for (const auto& uuid : catalog.getAllCollectionUUIDsFromDb(_name)) { - auto collection = catalog.lookupCollectionByUUID(opCtx, uuid); + auto collection = catalog.lookupCollectionByUUIDForMetadataWrite(opCtx, uuid); invariant(collection); // If this is called from the repair path, the collection is already initialized. if (!collection->isInitialized()) @@ -360,7 +360,8 @@ Status DatabaseImpl::dropCollectionEvenIfSystem(OperationContext* opCtx, "dropCollection() cannot accept a valid drop optime when writes are replicated."); } - Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); + Collection* collection = + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, nss); if (!collection) { return Status::OK(); // Post condition already met. @@ -489,7 +490,7 @@ void DatabaseImpl::_dropCollectionIndexes(OperationContext* opCtx, Status DatabaseImpl::_finishDropCollection(OperationContext* opCtx, const NamespaceString& nss, - Collection* collection) const { + const Collection* collection) const { UUID uuid = collection->uuid(); LOGV2(20318, "Finishing collection drop for {namespace} ({uuid}).", @@ -527,7 +528,7 @@ Status DatabaseImpl::renameCollection(OperationContext* opCtx, } Collection* collToRename = - CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, fromNss); + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, fromNss); if (!collToRename) { return Status(ErrorCodes::NamespaceNotFound, "collection not found to rename"); } @@ -818,7 +819,8 @@ void DatabaseImpl::checkForIdIndexesAndDropPendingCollections(OperationContext* if (nss.isSystem()) continue; - Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); + const Collection* coll = + CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); if (!coll) continue; diff --git a/src/mongo/db/catalog/database_impl.h b/src/mongo/db/catalog/database_impl.h index 19a24c9f8e4..a1a7f9a153e 100644 --- a/src/mongo/db/catalog/database_impl.h +++ b/src/mongo/db/catalog/database_impl.h @@ -137,7 +137,7 @@ private: */ Status _finishDropCollection(OperationContext* opCtx, const NamespaceString& nss, - Collection* collection) const; + const Collection* collection) const; /** * Removes all indexes for a collection. diff --git a/src/mongo/db/catalog/drop_collection.cpp b/src/mongo/db/catalog/drop_collection.cpp index 69a7eaadc58..c3470d56941 100644 --- a/src/mongo/db/catalog/drop_collection.cpp +++ b/src/mongo/db/catalog/drop_collection.cpp @@ -53,7 +53,7 @@ namespace mongo { MONGO_FAIL_POINT_DEFINE(hangDropCollectionBeforeLockAcquisition); MONGO_FAIL_POINT_DEFINE(hangDuringDropCollection); -Status _checkNssAndReplState(OperationContext* opCtx, Collection* coll) { +Status _checkNssAndReplState(OperationContext* opCtx, const Collection* coll) { if (!coll) { return Status(ErrorCodes::NamespaceNotFound, "ns not found"); } @@ -134,7 +134,7 @@ Status _abortIndexBuildsAndDropCollection(OperationContext* opCtx, // which may have changed when we released the collection lock temporarily. opCtx->recoveryUnit()->abandonSnapshot(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, startingNss); Status status = _checkNssAndReplState(opCtx, coll); if (!status.isOK()) { @@ -185,7 +185,8 @@ Status _abortIndexBuildsAndDropCollection(OperationContext* opCtx, // disk state, which may have changed when we released the collection lock temporarily. opCtx->recoveryUnit()->abandonSnapshot(); - coll = CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, collectionUUID); + const Collection* coll = + CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, collectionUUID); status = _checkNssAndReplState(opCtx, coll); if (!status.isOK()) { return status; @@ -236,7 +237,7 @@ Status _dropCollection(OperationContext* opCtx, DropCollectionSystemCollectionMode systemCollectionMode, BSONObjBuilder& result) { Lock::CollectionLock collLock(opCtx, collectionName, MODE_X); - Collection* coll = + const Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, collectionName); Status status = _checkNssAndReplState(opCtx, coll); if (!status.isOK()) { @@ -299,7 +300,7 @@ Status dropCollection(OperationContext* opCtx, return Status(ErrorCodes::NamespaceNotFound, "ns not found"); } - Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( + const Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( opCtx, collectionName); if (!coll) { @@ -336,7 +337,7 @@ Status dropCollectionForApplyOps(OperationContext* opCtx, return Status(ErrorCodes::NamespaceNotFound, "ns not found"); } - Collection* coll = + const Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, collectionName); BSONObjBuilder unusedBuilder; diff --git a/src/mongo/db/catalog/drop_indexes.cpp b/src/mongo/db/catalog/drop_indexes.cpp index 498c9421d1e..f44a977ae49 100644 --- a/src/mongo/db/catalog/drop_indexes.cpp +++ b/src/mongo/db/catalog/drop_indexes.cpp @@ -60,7 +60,7 @@ constexpr auto kIndexFieldName = "index"_sd; Status checkView(OperationContext* opCtx, const NamespaceString& nss, Database* db, - Collection* collection) { + const Collection* collection) { if (!collection) { if (db && ViewCatalog::get(db)->lookup(opCtx, nss.ns())) { return Status(ErrorCodes::CommandNotSupportedOnView, @@ -73,7 +73,7 @@ Status checkView(OperationContext* opCtx, Status checkReplState(OperationContext* opCtx, NamespaceStringOrUUID dbAndUUID, - Collection* collection) { + const Collection* collection) { auto replCoord = repl::ReplicationCoordinator::get(opCtx); auto canAcceptWrites = replCoord->canAcceptWritesFor(opCtx, dbAndUUID); bool writesAreReplicatedAndNotPrimary = opCtx->writesAreReplicated() && !canAcceptWrites; @@ -101,7 +101,7 @@ Status checkReplState(OperationContext* opCtx, * Validates the key pattern passed through the command. */ StatusWith<const IndexDescriptor*> getDescriptorByKeyPattern(OperationContext* opCtx, - IndexCatalog* indexCatalog, + const IndexCatalog* indexCatalog, const BSONElement& keyPattern) { const bool includeUnfinished = true; std::vector<const IndexDescriptor*> indexes; @@ -142,7 +142,7 @@ StatusWith<const IndexDescriptor*> getDescriptorByKeyPattern(OperationContext* o * to be held to look up the index name from the key pattern. */ StatusWith<std::vector<std::string>> getIndexNames(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const BSONElement& indexElem) { invariant(opCtx->lockState()->isCollectionLockedForMode(collection->ns(), MODE_IX)); @@ -187,7 +187,7 @@ std::vector<UUID> abortIndexBuildByIndexNames(OperationContext* opCtx, * Drops single index given a descriptor. */ Status dropIndexByDescriptor(OperationContext* opCtx, - Collection* collection, + const Collection* collection, IndexCatalog* indexCatalog, const IndexDescriptor* desc) { if (desc->isIdIndex()) { @@ -324,7 +324,7 @@ Status dropIndexes(OperationContext* opCtx, autoColl.emplace(opCtx, nss, MODE_IX); Database* db = autoColl->getDb(); - Collection* collection = autoColl->getCollection(); + Collection* collection = autoColl->getWritableCollection(); Status status = checkView(opCtx, nss, db, collection); if (!status.isOK()) { return status; @@ -407,7 +407,7 @@ Status dropIndexes(OperationContext* opCtx, opCtx->recoveryUnit()->abandonSnapshot(); db = autoColl->getDb(); - collection = autoColl->getCollection(); + collection = autoColl->getWritableCollection(); if (!collection) { return Status(ErrorCodes::NamespaceNotFound, str::stream() @@ -506,12 +506,11 @@ Status dropIndexesForApplyOps(OperationContext* opCtx, const BSONObj& cmdObj, BSONObjBuilder* result) { return writeConflictRetry(opCtx, "dropIndexes", nss.db(), [opCtx, &nss, &cmdObj, result] { - AutoGetCollection autoColl(opCtx, nss, MODE_X); + AutoGetCollection collection(opCtx, nss, MODE_X); // If db/collection does not exist, short circuit and return. - Database* db = autoColl.getDb(); - Collection* collection = autoColl.getCollection(); - Status status = checkView(opCtx, nss, db, collection); + Database* db = collection.getDb(); + Status status = checkView(opCtx, nss, db, collection.getCollection()); if (!status.isOK()) { return status; } @@ -527,7 +526,7 @@ Status dropIndexesForApplyOps(OperationContext* opCtx, collection->uuid()); BSONElement indexElem = cmdObj.getField(kIndexFieldName); - auto swIndexNames = getIndexNames(opCtx, collection, indexElem); + auto swIndexNames = getIndexNames(opCtx, collection.getCollection(), indexElem); if (!swIndexNames.isOK()) { return swIndexNames.getStatus(); } @@ -539,7 +538,8 @@ Status dropIndexesForApplyOps(OperationContext* opCtx, // Use an empty BSONObjBuilder to avoid duplicate appends to result on retry loops. BSONObjBuilder tempObjBuilder; - status = dropReadyIndexes(opCtx, collection, swIndexNames.getValue(), &tempObjBuilder); + status = dropReadyIndexes( + opCtx, collection.getWritableCollection(), swIndexNames.getValue(), &tempObjBuilder); if (!status.isOK()) { return status; } diff --git a/src/mongo/db/catalog/index_build_block.cpp b/src/mongo/db/catalog/index_build_block.cpp index 6d7eee87a8b..381d8d09ecb 100644 --- a/src/mongo/db/catalog/index_build_block.cpp +++ b/src/mongo/db/catalog/index_build_block.cpp @@ -178,7 +178,7 @@ IndexBuildBlock::~IndexBuildBlock() { // Don't need to call fail() here, as rollback will clean everything up for us. } -void IndexBuildBlock::fail(OperationContext* opCtx, const Collection* collection) { +void IndexBuildBlock::fail(OperationContext* opCtx, Collection* collection) { // Being in a WUOW means all timestamping responsibility can be pushed up to the caller. invariant(opCtx->lockState()->inAWriteUnitOfWork()); diff --git a/src/mongo/db/catalog/index_build_block.h b/src/mongo/db/catalog/index_build_block.h index ff7f36f6016..22b65a4a541 100644 --- a/src/mongo/db/catalog/index_build_block.h +++ b/src/mongo/db/catalog/index_build_block.h @@ -91,7 +91,7 @@ public: * * Must be called from within a `WriteUnitOfWork` */ - void fail(OperationContext* opCtx, const Collection* collection); + void fail(OperationContext* opCtx, Collection* collection); /** * Returns the IndexCatalogEntry that was created in init(). diff --git a/src/mongo/db/catalog/index_builds_manager.cpp b/src/mongo/db/catalog/index_builds_manager.cpp index 2a72b40fb71..15f355bf9c0 100644 --- a/src/mongo/db/catalog/index_builds_manager.cpp +++ b/src/mongo/db/catalog/index_builds_manager.cpp @@ -121,7 +121,7 @@ Status IndexBuildsManager::setUpIndexBuild(OperationContext* opCtx, } Status IndexBuildsManager::startBuildingIndex(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const UUID& buildUUID, boost::optional<RecordId> resumeAfterRecordId) { auto builder = invariant(_getBuilder(buildUUID)); @@ -277,7 +277,7 @@ Status IndexBuildsManager::drainBackgroundWrites( Status IndexBuildsManager::retrySkippedRecords(OperationContext* opCtx, const UUID& buildUUID, - Collection* collection) { + const Collection* collection) { auto builder = invariant(_getBuilder(buildUUID)); return builder->retrySkippedRecords(opCtx, collection); } @@ -331,7 +331,7 @@ bool IndexBuildsManager::abortIndexBuild(OperationContext* opCtx, } bool IndexBuildsManager::abortIndexBuildWithoutCleanupForRollback(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const UUID& buildUUID, bool isResumable) { auto builder = _getBuilder(buildUUID); @@ -352,7 +352,7 @@ bool IndexBuildsManager::abortIndexBuildWithoutCleanupForRollback(OperationConte } bool IndexBuildsManager::abortIndexBuildWithoutCleanupForShutdown(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const UUID& buildUUID, bool isResumable) { auto builder = _getBuilder(buildUUID); @@ -410,7 +410,7 @@ StatusWith<int> IndexBuildsManager::_moveRecordToLostAndFound( invariant(opCtx->lockState()->isCollectionLockedForMode(nss, MODE_IX)); auto originalCollection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); - Collection* localCollection = + const Collection* localCollection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, lostAndFoundNss); // Create the collection if it doesn't exist. diff --git a/src/mongo/db/catalog/index_builds_manager.h b/src/mongo/db/catalog/index_builds_manager.h index 87004b6f2f8..c48902425f2 100644 --- a/src/mongo/db/catalog/index_builds_manager.h +++ b/src/mongo/db/catalog/index_builds_manager.h @@ -96,7 +96,7 @@ public: * Runs the scanning/insertion phase of the index build.. */ Status startBuildingIndex(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const UUID& buildUUID, boost::optional<RecordId> resumeAfterRecordId = boost::none); @@ -126,7 +126,7 @@ public: */ Status retrySkippedRecords(OperationContext* opCtx, const UUID& buildUUID, - Collection* collection); + const Collection* collection); /** * Runs the index constraint violation checking phase of the index build.. @@ -163,7 +163,7 @@ public: * been cleared away, or not having yet started.. */ bool abortIndexBuildWithoutCleanupForRollback(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const UUID& buildUUID, bool isResumable); @@ -173,7 +173,7 @@ public: * index build and resumable index builds are supported. */ bool abortIndexBuildWithoutCleanupForShutdown(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const UUID& buildUUID, bool isResumable); diff --git a/src/mongo/db/catalog/index_builds_manager_test.cpp b/src/mongo/db/catalog/index_builds_manager_test.cpp index 1cd28267947..b8c1ca36993 100644 --- a/src/mongo/db/catalog/index_builds_manager_test.cpp +++ b/src/mongo/db/catalog/index_builds_manager_test.cpp @@ -84,13 +84,13 @@ TEST_F(IndexBuildsManagerTest, IndexBuildsManagerSetUpAndTearDown) { auto specs = makeSpecs(_nss, {"a", "b"}); ASSERT_OK(_indexBuildsManager.setUpIndexBuild(operationContext(), - autoColl.getCollection(), + autoColl.getWritableCollection(), specs, _buildUUID, MultiIndexBlock::kNoopOnInitFn)); _indexBuildsManager.abortIndexBuild(operationContext(), - autoColl.getCollection(), + autoColl.getWritableCollection(), _buildUUID, MultiIndexBlock::kNoopOnCleanUpFn); _indexBuildsManager.unregisterIndexBuild(_buildUUID); diff --git a/src/mongo/db/catalog/index_catalog.h b/src/mongo/db/catalog/index_catalog.h index c33e8f9969b..f32db23787f 100644 --- a/src/mongo/db/catalog/index_catalog.h +++ b/src/mongo/db/catalog/index_catalog.h @@ -410,9 +410,9 @@ public: * See IndexCatalogEntry::setMultikey(). */ virtual void setMultikeyPaths(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const IndexDescriptor* const desc, - const MultikeyPaths& multikeyPaths) = 0; + const MultikeyPaths& multikeyPaths) const = 0; // ----- data modifiers ------ @@ -423,7 +423,7 @@ public: * This method may throw. */ virtual Status indexRecords(OperationContext* const opCtx, - Collection* collection, + const Collection* collection, const std::vector<BsonRecord>& bsonRecords, int64_t* const keysInsertedOut) = 0; @@ -434,7 +434,7 @@ public: * This method may throw. */ virtual Status updateRecord(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const BSONObj& oldDoc, const BSONObj& newDoc, const RecordId& recordId, @@ -455,7 +455,7 @@ public: * Attempt compaction on all ready indexes to regain disk space, if the storage engine's index * supports compaction in-place. */ - virtual Status compactIndexes(OperationContext* opCtx) = 0; + virtual Status compactIndexes(OperationContext* opCtx) const = 0; virtual std::string getAccessMethodName(const BSONObj& keyPattern) = 0; diff --git a/src/mongo/db/catalog/index_catalog_impl.cpp b/src/mongo/db/catalog/index_catalog_impl.cpp index 3bc9681824b..d306b385540 100644 --- a/src/mongo/db/catalog/index_catalog_impl.cpp +++ b/src/mongo/db/catalog/index_catalog_impl.cpp @@ -1105,9 +1105,9 @@ void IndexCatalogImpl::deleteIndexFromDisk(OperationContext* opCtx, const string } void IndexCatalogImpl::setMultikeyPaths(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const IndexDescriptor* desc, - const MultikeyPaths& multikeyPaths) { + const MultikeyPaths& multikeyPaths) const { IndexCatalogEntry* entry = desc->getEntry(); invariant(entry); entry->setMultikey(opCtx, coll, multikeyPaths); @@ -1332,7 +1332,7 @@ const IndexDescriptor* IndexCatalogImpl::refreshEntry(OperationContext* opCtx, // --------------------------- Status IndexCatalogImpl::_indexKeys(OperationContext* opCtx, - Collection* coll, + const Collection* coll, IndexCatalogEntry* index, const KeyStringSet& keys, const KeyStringSet& multikeyMetadataKeys, @@ -1385,7 +1385,7 @@ Status IndexCatalogImpl::_indexKeys(OperationContext* opCtx, } Status IndexCatalogImpl::_indexFilteredRecords(OperationContext* opCtx, - Collection* coll, + const Collection* coll, IndexCatalogEntry* index, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut) { @@ -1436,7 +1436,7 @@ Status IndexCatalogImpl::_indexFilteredRecords(OperationContext* opCtx, } Status IndexCatalogImpl::_indexRecords(OperationContext* opCtx, - Collection* coll, + const Collection* coll, IndexCatalogEntry* index, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut) { @@ -1458,7 +1458,7 @@ Status IndexCatalogImpl::_indexRecords(OperationContext* opCtx, } Status IndexCatalogImpl::_updateRecord(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, IndexCatalogEntry* index, const BSONObj& oldDoc, const BSONObj& newDoc, @@ -1599,7 +1599,7 @@ void IndexCatalogImpl::_unindexRecord(OperationContext* opCtx, } Status IndexCatalogImpl::indexRecords(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut) { if (keysInsertedOut) { @@ -1622,7 +1622,7 @@ Status IndexCatalogImpl::indexRecords(OperationContext* opCtx, } Status IndexCatalogImpl::updateRecord(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const BSONObj& oldDoc, const BSONObj& newDoc, const RecordId& recordId, @@ -1684,7 +1684,7 @@ void IndexCatalogImpl::unindexRecord(OperationContext* opCtx, } } -Status IndexCatalogImpl::compactIndexes(OperationContext* opCtx) { +Status IndexCatalogImpl::compactIndexes(OperationContext* opCtx) const { for (IndexCatalogEntryContainer::const_iterator it = _readyIndexes.begin(); it != _readyIndexes.end(); ++it) { @@ -1772,7 +1772,7 @@ void IndexCatalogImpl::indexBuildSuccess(OperationContext* opCtx, } StatusWith<BSONObj> IndexCatalogImpl::_fixIndexSpec(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const BSONObj& spec) const { auto statusWithSpec = adjustIndexSpecObject(spec); if (!statusWithSpec.isOK()) { diff --git a/src/mongo/db/catalog/index_catalog_impl.h b/src/mongo/db/catalog/index_catalog_impl.h index 85dc5ebe7d8..026402c7a3b 100644 --- a/src/mongo/db/catalog/index_catalog_impl.h +++ b/src/mongo/db/catalog/index_catalog_impl.h @@ -221,9 +221,9 @@ public: // ---- modify single index void setMultikeyPaths(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const IndexDescriptor* desc, - const MultikeyPaths& multikeyPaths) override; + const MultikeyPaths& multikeyPaths) const override; // ----- data modifiers ------ @@ -234,7 +234,7 @@ public: * This method may throw. */ Status indexRecords(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut) override; @@ -242,7 +242,7 @@ public: * See IndexCatalog::updateRecord */ Status updateRecord(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const BSONObj& oldDoc, const BSONObj& newDoc, const RecordId& recordId, @@ -258,7 +258,7 @@ public: bool noWarn, int64_t* keysDeletedOut) override; - Status compactIndexes(OperationContext* opCtx) override; + Status compactIndexes(OperationContext* opCtx) const override; inline std::string getAccessMethodName(const BSONObj& keyPattern) override { return _getAccessMethodName(keyPattern); @@ -295,7 +295,7 @@ private: std::string _getAccessMethodName(const BSONObj& keyPattern) const; Status _indexKeys(OperationContext* opCtx, - Collection* coll, + const Collection* coll, IndexCatalogEntry* index, const KeyStringSet& keys, const KeyStringSet& multikeyMetadataKeys, @@ -306,19 +306,19 @@ private: int64_t* keysInsertedOut); Status _indexFilteredRecords(OperationContext* opCtx, - Collection* coll, + const Collection* coll, IndexCatalogEntry* index, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut); Status _indexRecords(OperationContext* opCtx, - Collection* coll, + const Collection* coll, IndexCatalogEntry* index, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut); Status _updateRecord(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, IndexCatalogEntry* index, const BSONObj& oldDoc, const BSONObj& newDoc, @@ -347,7 +347,7 @@ private: * plugin-level transformations if appropriate, etc. */ StatusWith<BSONObj> _fixIndexSpec(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const BSONObj& spec) const; Status _isSpecOk(OperationContext* opCtx, const BSONObj& spec) const; diff --git a/src/mongo/db/catalog/index_catalog_noop.h b/src/mongo/db/catalog/index_catalog_noop.h index 92b74cfc84e..9cc63d34ed5 100644 --- a/src/mongo/db/catalog/index_catalog_noop.h +++ b/src/mongo/db/catalog/index_catalog_noop.h @@ -194,19 +194,19 @@ public: } void setMultikeyPaths(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const IndexDescriptor* const desc, - const MultikeyPaths& multikeyPaths) override {} + const MultikeyPaths& multikeyPaths) const override {} Status indexRecords(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const std::vector<BsonRecord>& bsonRecords, int64_t* const keysInsertedOut) override { return Status::OK(); } Status updateRecord(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const BSONObj& oldDoc, const BSONObj& newDoc, const RecordId& recordId, diff --git a/src/mongo/db/catalog/index_signature_test.cpp b/src/mongo/db/catalog/index_signature_test.cpp index 842093f40e5..ca5ee599308 100644 --- a/src/mongo/db/catalog/index_signature_test.cpp +++ b/src/mongo/db/catalog/index_signature_test.cpp @@ -69,7 +69,7 @@ public: } Collection* coll() const { - return _coll->getCollection(); + return _coll->getWritableCollection(); } OperationContext* opCtx() { diff --git a/src/mongo/db/catalog/multi_index_block.cpp b/src/mongo/db/catalog/multi_index_block.cpp index 05e61d37004..09a728ebced 100644 --- a/src/mongo/db/catalog/multi_index_block.cpp +++ b/src/mongo/db/catalog/multi_index_block.cpp @@ -394,7 +394,7 @@ StatusWith<std::vector<BSONObj>> MultiIndexBlock::init( Status MultiIndexBlock::insertAllDocumentsInCollection( OperationContext* opCtx, - Collection* collection, + const Collection* collection, boost::optional<RecordId> resumeAfterRecordId) { invariant(!_buildIsCleanedUp); invariant(opCtx->lockState()->isNoop() || !opCtx->lockState()->inAWriteUnitOfWork()); @@ -714,7 +714,7 @@ Status MultiIndexBlock::drainBackgroundWrites( return Status::OK(); } -Status MultiIndexBlock::retrySkippedRecords(OperationContext* opCtx, Collection* collection) { +Status MultiIndexBlock::retrySkippedRecords(OperationContext* opCtx, const Collection* collection) { invariant(!_buildIsCleanedUp); for (auto&& index : _indexes) { auto interceptor = index.block->getEntry()->indexBuildInterceptor(); diff --git a/src/mongo/db/catalog/multi_index_block.h b/src/mongo/db/catalog/multi_index_block.h index 100f17a359d..8a9b4b6e27e 100644 --- a/src/mongo/db/catalog/multi_index_block.h +++ b/src/mongo/db/catalog/multi_index_block.h @@ -120,7 +120,7 @@ public: const BSONObj& spec, OnInitFn onInit); StatusWith<std::vector<BSONObj>> initForResume(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const std::vector<BSONObj>& specs, const ResumeIndexInfo& resumeInfo); @@ -151,7 +151,7 @@ public: */ Status insertAllDocumentsInCollection( OperationContext* opCtx, - Collection* collection, + const Collection* collection, boost::optional<RecordId> resumeAfterRecordId = boost::none); /** @@ -206,7 +206,7 @@ public: * of an index build, so it must ensure that before it finishes, it has indexed all documents in * a collection, requiring a call to this function upon completion. */ - Status retrySkippedRecords(OperationContext* opCtx, Collection* collection); + Status retrySkippedRecords(OperationContext* opCtx, const Collection* collection); /** * Check any constraits that may have been temporarily violated during the index build for diff --git a/src/mongo/db/catalog/multi_index_block_test.cpp b/src/mongo/db/catalog/multi_index_block_test.cpp index ed5da9d7957..4f379451bec 100644 --- a/src/mongo/db/catalog/multi_index_block_test.cpp +++ b/src/mongo/db/catalog/multi_index_block_test.cpp @@ -90,11 +90,12 @@ void MultiIndexBlockTest::tearDown() { TEST_F(MultiIndexBlockTest, CommitWithoutInsertingDocuments) { auto indexer = getIndexer(); - AutoGetCollection autoColl(operationContext(), getNSS(), MODE_X); - Collection* coll = autoColl.getCollection(); + AutoGetCollection coll(operationContext(), getNSS(), MODE_X); - auto specs = unittest::assertGet(indexer->init( - operationContext(), coll, std::vector<BSONObj>(), MultiIndexBlock::kNoopOnInitFn)); + auto specs = unittest::assertGet(indexer->init(operationContext(), + coll.getWritableCollection(), + std::vector<BSONObj>(), + MultiIndexBlock::kNoopOnInitFn)); ASSERT_EQUALS(0U, specs.size()); ASSERT_OK(indexer->dumpInsertsFromBulk(operationContext())); @@ -103,7 +104,7 @@ TEST_F(MultiIndexBlockTest, CommitWithoutInsertingDocuments) { { WriteUnitOfWork wunit(operationContext()); ASSERT_OK(indexer->commit(operationContext(), - coll, + coll.getWritableCollection(), MultiIndexBlock::kNoopOnCreateEachFn, MultiIndexBlock::kNoopOnCommitFn)); wunit.commit(); @@ -113,11 +114,12 @@ TEST_F(MultiIndexBlockTest, CommitWithoutInsertingDocuments) { TEST_F(MultiIndexBlockTest, CommitAfterInsertingSingleDocument) { auto indexer = getIndexer(); - AutoGetCollection autoColl(operationContext(), getNSS(), MODE_X); - Collection* coll = autoColl.getCollection(); + AutoGetCollection coll(operationContext(), getNSS(), MODE_X); - auto specs = unittest::assertGet(indexer->init( - operationContext(), coll, std::vector<BSONObj>(), MultiIndexBlock::kNoopOnInitFn)); + auto specs = unittest::assertGet(indexer->init(operationContext(), + coll.getWritableCollection(), + std::vector<BSONObj>(), + MultiIndexBlock::kNoopOnInitFn)); ASSERT_EQUALS(0U, specs.size()); ASSERT_OK(indexer->insertSingleDocumentForInitialSyncOrRecovery(operationContext(), {}, {})); @@ -127,24 +129,26 @@ TEST_F(MultiIndexBlockTest, CommitAfterInsertingSingleDocument) { { WriteUnitOfWork wunit(operationContext()); ASSERT_OK(indexer->commit(operationContext(), - coll, + coll.getWritableCollection(), MultiIndexBlock::kNoopOnCreateEachFn, MultiIndexBlock::kNoopOnCommitFn)); wunit.commit(); } // abort() should have no effect after the index build is committed. - indexer->abortIndexBuild(operationContext(), coll, MultiIndexBlock::kNoopOnCleanUpFn); + indexer->abortIndexBuild( + operationContext(), coll.getWritableCollection(), MultiIndexBlock::kNoopOnCleanUpFn); } TEST_F(MultiIndexBlockTest, AbortWithoutCleanupAfterInsertingSingleDocument) { auto indexer = getIndexer(); - AutoGetCollection autoColl(operationContext(), getNSS(), MODE_X); - Collection* coll = autoColl.getCollection(); + AutoGetCollection coll(operationContext(), getNSS(), MODE_X); - auto specs = unittest::assertGet(indexer->init( - operationContext(), coll, std::vector<BSONObj>(), MultiIndexBlock::kNoopOnInitFn)); + auto specs = unittest::assertGet(indexer->init(operationContext(), + coll.getWritableCollection(), + std::vector<BSONObj>(), + MultiIndexBlock::kNoopOnInitFn)); ASSERT_EQUALS(0U, specs.size()); ASSERT_OK(indexer->insertSingleDocumentForInitialSyncOrRecovery(operationContext(), {}, {})); auto isResumable = false; @@ -154,8 +158,7 @@ TEST_F(MultiIndexBlockTest, AbortWithoutCleanupAfterInsertingSingleDocument) { TEST_F(MultiIndexBlockTest, InitWriteConflictException) { auto indexer = getIndexer(); - AutoGetCollection autoColl(operationContext(), getNSS(), MODE_X); - Collection* coll = autoColl.getCollection(); + AutoGetCollection coll(operationContext(), getNSS(), MODE_X); BSONObj spec = BSON("key" << BSON("a" << 1) << "name" << "a_1" @@ -164,7 +167,7 @@ TEST_F(MultiIndexBlockTest, InitWriteConflictException) { { WriteUnitOfWork wuow(operationContext()); ASSERT_THROWS_CODE(indexer->init(operationContext(), - coll, + coll.getWritableCollection(), {spec}, [](std::vector<BSONObj>& specs) -> Status { throw WriteConflictException(); @@ -175,12 +178,17 @@ TEST_F(MultiIndexBlockTest, InitWriteConflictException) { { WriteUnitOfWork wuow(operationContext()); - ASSERT_OK(indexer->init(operationContext(), coll, {spec}, MultiIndexBlock::kNoopOnInitFn) + ASSERT_OK(indexer + ->init(operationContext(), + coll.getWritableCollection(), + {spec}, + MultiIndexBlock::kNoopOnInitFn) .getStatus()); wuow.commit(); } - indexer->abortIndexBuild(operationContext(), coll, MultiIndexBlock::kNoopOnCleanUpFn); + indexer->abortIndexBuild( + operationContext(), coll.getWritableCollection(), MultiIndexBlock::kNoopOnCleanUpFn); } } // namespace diff --git a/src/mongo/db/catalog/rename_collection.cpp b/src/mongo/db/catalog/rename_collection.cpp index c0d13ed746c..111629b3fb4 100644 --- a/src/mongo/db/catalog/rename_collection.cpp +++ b/src/mongo/db/catalog/rename_collection.cpp @@ -110,7 +110,7 @@ Status checkSourceAndTargetNamespaces(OperationContext* opCtx, str::stream() << "Database " << source.db() << " does not exist or is drop pending"); - Collection* const sourceColl = + const auto sourceColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, source); if (!sourceColl) { if (ViewCatalog::get(db)->lookup(opCtx, source.ns())) @@ -122,7 +122,7 @@ Status checkSourceAndTargetNamespaces(OperationContext* opCtx, IndexBuildsCoordinator::get(opCtx)->assertNoIndexBuildInProgForCollection(sourceColl->uuid()); - Collection* targetColl = + const auto targetColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, target); if (!targetColl) { @@ -220,7 +220,7 @@ Status renameCollectionAndDropTarget(OperationContext* opCtx, OptionalCollectionUUID uuid, NamespaceString source, NamespaceString target, - Collection* targetColl, + const Collection* targetColl, RenameCollectionOptions options, repl::OpTime renameOpTimeFromApplyOps) { return writeConflictRetry(opCtx, "renameCollection", target.ns(), [&] { @@ -319,9 +319,9 @@ Status renameCollectionWithinDB(OperationContext* opCtx, return status; auto db = DatabaseHolder::get(opCtx)->getDb(opCtx, source.db()); - Collection* const sourceColl = + const auto sourceColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, source); - Collection* const targetColl = + const auto targetColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, target); AutoStatsTracker statsTracker( @@ -362,7 +362,7 @@ Status renameCollectionWithinDBForApplyOps(OperationContext* opCtx, return status; auto db = DatabaseHolder::get(opCtx)->getDb(opCtx, source.db()); - Collection* const sourceColl = + const auto sourceColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, source); AutoStatsTracker statsTracker( @@ -373,8 +373,7 @@ Status renameCollectionWithinDBForApplyOps(OperationContext* opCtx, CollectionCatalog::get(opCtx).getDatabaseProfileLevel(source.db())); return writeConflictRetry(opCtx, "renameCollection", target.ns(), [&] { - Collection* targetColl = - CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, target); + auto targetColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, target); WriteUnitOfWork wuow(opCtx); if (targetColl) { if (sourceColl->uuid() == targetColl->uuid()) { @@ -491,7 +490,7 @@ Status renameBetweenDBs(OperationContext* opCtx, AutoStatsTracker::LogMode::kUpdateCurOp, CollectionCatalog::get(opCtx).getDatabaseProfileLevel(source.db())); - Collection* const sourceColl = + const auto sourceColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, source); if (!sourceColl) { if (sourceDB && ViewCatalog::get(sourceDB)->lookup(opCtx, source.ns())) @@ -515,7 +514,7 @@ Status renameBetweenDBs(OperationContext* opCtx, // Check if the target namespace exists and if dropTarget is true. // Return a non-OK status if target exists and dropTarget is not true or if the collection // is sharded. - Collection* targetColl = targetDB + const auto targetColl = targetDB ? CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, target) : nullptr; if (targetColl) { @@ -564,7 +563,7 @@ Status renameBetweenDBs(OperationContext* opCtx, "temporaryCollection"_attr = tmpName, "sourceCollection"_attr = source); - Collection* tmpColl = nullptr; + const Collection* tmpColl = nullptr; { auto collectionOptions = DurableCatalog::get(opCtx)->getCollectionOptions(opCtx, sourceColl->getCatalogId()); diff --git a/src/mongo/db/catalog/rename_collection_test.cpp b/src/mongo/db/catalog/rename_collection_test.cpp index fc8beb3d713..31895d624f8 100644 --- a/src/mongo/db/catalog/rename_collection_test.cpp +++ b/src/mongo/db/catalog/rename_collection_test.cpp @@ -110,7 +110,7 @@ public: bool fromMigrate) override; void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, @@ -224,7 +224,7 @@ void OpObserverMock::onInserts(OperationContext* opCtx, } void OpObserverMock::onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, @@ -439,7 +439,7 @@ CollectionUUID _getCollectionUuid(OperationContext* opCtx, const NamespaceString * Get collection namespace by UUID. */ NamespaceString _getCollectionNssFromUUID(OperationContext* opCtx, const UUID& uuid) { - Collection* source = CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, uuid); + const Collection* source = CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, uuid); return source ? source->ns() : NamespaceString(); } @@ -462,16 +462,15 @@ void _createIndexOnEmptyCollection(OperationContext* opCtx, const NamespaceString& nss, const std::string& indexName) { writeConflictRetry(opCtx, "_createIndexOnEmptyCollection", nss.ns(), [=] { - AutoGetCollection autoColl(opCtx, nss, MODE_X); - auto collection = autoColl.getCollection(); + AutoGetCollection collection(opCtx, nss, MODE_X); ASSERT_TRUE(collection) << "Cannot create index on empty collection " << nss << " because collection " << nss << " does not exist."; auto indexInfoObj = BSON("v" << int(IndexDescriptor::kLatestIndexVersion) << "key" << BSON("a" << 1) << "name" << indexName); - auto indexCatalog = collection->getIndexCatalog(); WriteUnitOfWork wuow(opCtx); + auto indexCatalog = collection.getWritableCollection()->getIndexCatalog(); ASSERT_OK(indexCatalog->createIndexOnEmptyCollection(opCtx, indexInfoObj).getStatus()); wuow.commit(); }); @@ -500,7 +499,7 @@ void _insertDocument(OperationContext* opCtx, const NamespaceString& nss, const * Retrieves the pointer to a collection associated with the given namespace string from the * catalog. The caller must hold the appropriate locks from the lock manager. */ -Collection* _getCollection_inlock(OperationContext* opCtx, const NamespaceString& nss) { +const Collection* _getCollection_inlock(OperationContext* opCtx, const NamespaceString& nss) { invariant(opCtx->lockState()->isCollectionLockedForMode(nss, MODE_IS)); auto databaseHolder = DatabaseHolder::get(opCtx); auto* db = databaseHolder->getDb(opCtx, nss.db()); @@ -1186,14 +1185,14 @@ TEST_F(RenameCollectionTest, CollectionPointerRemainsValidThroughRename) { // Get a pointer to the source collection, and ensure that it reports the expected namespace // string. - Collection* sourceColl = _getCollection_inlock(_opCtx.get(), _sourceNss); + const Collection* sourceColl = _getCollection_inlock(_opCtx.get(), _sourceNss); ASSERT(sourceColl); ASSERT_OK(renameCollection(_opCtx.get(), _sourceNss, _targetNss, {})); // Retrieve the pointer associated with the target namespace, and ensure that its the same // pointer (i.e. the renamed collection has the very same Collection instance). - Collection* targetColl = _getCollection_inlock(_opCtx.get(), _targetNss); + const Collection* targetColl = _getCollection_inlock(_opCtx.get(), _targetNss); ASSERT(targetColl); ASSERT_EQ(targetColl, sourceColl); @@ -1224,7 +1223,7 @@ TEST_F(RenameCollectionTest, CollectionCatalogMappingRemainsIntactThroughRename) Lock::DBLock sourceLk(_opCtx.get(), _sourceNss.db(), MODE_X); Lock::DBLock targetLk(_opCtx.get(), _targetNss.db(), MODE_X); auto& catalog = CollectionCatalog::get(_opCtx.get()); - Collection* sourceColl = _getCollection_inlock(_opCtx.get(), _sourceNss); + const Collection* sourceColl = _getCollection_inlock(_opCtx.get(), _sourceNss); ASSERT(sourceColl); ASSERT_EQ(sourceColl, catalog.lookupCollectionByUUID(_opCtx.get(), sourceColl->uuid())); ASSERT_OK(renameCollection(_opCtx.get(), _sourceNss, _targetNss, {})); diff --git a/src/mongo/db/catalog/throttle_cursor_test.cpp b/src/mongo/db/catalog/throttle_cursor_test.cpp index 0172ea1d0ad..91097350d36 100644 --- a/src/mongo/db/catalog/throttle_cursor_test.cpp +++ b/src/mongo/db/catalog/throttle_cursor_test.cpp @@ -59,7 +59,7 @@ public: Date_t getTime(); int64_t getDifferenceInMillis(Date_t start, Date_t end); - SortedDataInterfaceThrottleCursor getIdIndex(Collection* coll); + SortedDataInterfaceThrottleCursor getIdIndex(const Collection* coll); std::unique_ptr<DataThrottle> _dataThrottle; }; @@ -73,7 +73,7 @@ void ThrottleCursorTest::setUp() { // Insert random data into the collection. We don't need to create an index as the _id index is // created by default. AutoGetCollection autoColl(operationContext(), kNss, MODE_X); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); invariant(collection); OpDebug* const nullOpDebug = nullptr; @@ -108,7 +108,7 @@ int64_t ThrottleCursorTest::getDifferenceInMillis(Date_t start, Date_t end) { return end.toMillisSinceEpoch() - start.toMillisSinceEpoch(); } -SortedDataInterfaceThrottleCursor ThrottleCursorTest::getIdIndex(Collection* coll) { +SortedDataInterfaceThrottleCursor ThrottleCursorTest::getIdIndex(const Collection* coll) { const IndexDescriptor* idDesc = coll->getIndexCatalog()->findIdIndex(operationContext()); const IndexCatalogEntry* idEntry = coll->getIndexCatalog()->getEntry(idDesc); const IndexAccessMethod* iam = idEntry->accessMethod(); @@ -119,7 +119,7 @@ SortedDataInterfaceThrottleCursor ThrottleCursorTest::getIdIndex(Collection* col TEST_F(ThrottleCursorTest, TestSeekableRecordThrottleCursorOff) { auto opCtx = operationContext(); AutoGetCollection autoColl(opCtx, kNss, MODE_X); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); // Use a fixed record data size to simplify the timing calculations. FailPointEnableBlock failPoint("fixedCursorDataSizeOf512KBForDataThrottle"); @@ -152,7 +152,7 @@ TEST_F(ThrottleCursorTest, TestSeekableRecordThrottleCursorOff) { TEST_F(ThrottleCursorTest, TestSeekableRecordThrottleCursorOn) { auto opCtx = operationContext(); AutoGetCollection autoColl(opCtx, kNss, MODE_X); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); // Use a fixed record data size to simplify the timing calculations. FailPointEnableBlock failPoint("fixedCursorDataSizeOf512KBForDataThrottle"); @@ -204,7 +204,7 @@ TEST_F(ThrottleCursorTest, TestSeekableRecordThrottleCursorOn) { TEST_F(ThrottleCursorTest, TestSeekableRecordThrottleCursorOnLargeDocs) { auto opCtx = operationContext(); AutoGetCollection autoColl(opCtx, kNss, MODE_X); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); // Use a fixed record data size to simplify the timing calculations. FailPointEnableBlock failPoint("fixedCursorDataSizeOf2MBForDataThrottle"); @@ -265,7 +265,7 @@ TEST_F(ThrottleCursorTest, TestSeekableRecordThrottleCursorOnLargeDocs) { TEST_F(ThrottleCursorTest, TestSortedDataInterfaceThrottleCursorOff) { auto opCtx = operationContext(); AutoGetCollection autoColl(opCtx, kNss, MODE_X); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); // Use a fixed record data size to simplify the timing calculations. FailPointEnableBlock failPoint("fixedCursorDataSizeOf512KBForDataThrottle"); @@ -292,7 +292,7 @@ TEST_F(ThrottleCursorTest, TestSortedDataInterfaceThrottleCursorOff) { TEST_F(ThrottleCursorTest, TestSortedDataInterfaceThrottleCursorOn) { auto opCtx = operationContext(); AutoGetCollection autoColl(opCtx, kNss, MODE_X); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); // Use a fixed record data size to simplify the timing calculations. FailPointEnableBlock failPoint("fixedCursorDataSizeOf512KBForDataThrottle"); @@ -343,7 +343,7 @@ TEST_F(ThrottleCursorTest, TestSortedDataInterfaceThrottleCursorOn) { TEST_F(ThrottleCursorTest, TestMixedCursorsWithSharedThrottleOff) { auto opCtx = operationContext(); AutoGetCollection autoColl(opCtx, kNss, MODE_X); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); // Use a fixed record data size to simplify the timing calculations. FailPointEnableBlock failPoint("fixedCursorDataSizeOf512KBForDataThrottle"); @@ -385,7 +385,7 @@ TEST_F(ThrottleCursorTest, TestMixedCursorsWithSharedThrottleOff) { TEST_F(ThrottleCursorTest, TestMixedCursorsWithSharedThrottleOn) { auto opCtx = operationContext(); AutoGetCollection autoColl(opCtx, kNss, MODE_X); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); // Use a fixed record data size to simplify the timing calculations. FailPointEnableBlock failPoint("fixedCursorDataSizeOf512KBForDataThrottle"); diff --git a/src/mongo/db/catalog/validate_adaptor.cpp b/src/mongo/db/catalog/validate_adaptor.cpp index d1ac9037276..850c420e6e9 100644 --- a/src/mongo/db/catalog/validate_adaptor.cpp +++ b/src/mongo/db/catalog/validate_adaptor.cpp @@ -82,9 +82,8 @@ Status ValidateAdaptor::validateRecord(OperationContext* opCtx, LOGV2(4666601, "[validate]", "recordId"_attr = recordId, "recordData"_attr = recordBson); } - Collection* coll = _validateState->getCollection(); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); - if (!indexCatalog->haveAnyIndexes()) { + const Collection* coll = _validateState->getCollection(); + if (!coll->getIndexCatalog()->haveAnyIndexes()) { return status; } @@ -119,7 +118,8 @@ Status ValidateAdaptor::validateRecord(OperationContext* opCtx, if (_validateState->shouldRunRepair()) { writeConflictRetry(opCtx, "setIndexAsMultikey", coll->ns().ns(), [&] { WriteUnitOfWork wuow(opCtx); - indexCatalog->setMultikeyPaths(opCtx, coll, descriptor, *documentMultikeyPaths); + coll->getIndexCatalog()->setMultikeyPaths( + opCtx, coll, descriptor, *documentMultikeyPaths); wuow.commit(); }); @@ -149,7 +149,7 @@ Status ValidateAdaptor::validateRecord(OperationContext* opCtx, if (_validateState->shouldRunRepair()) { writeConflictRetry(opCtx, "increaseMultikeyPathCoverage", coll->ns().ns(), [&] { WriteUnitOfWork wuow(opCtx); - indexCatalog->setMultikeyPaths( + coll->getIndexCatalog()->setMultikeyPaths( opCtx, coll, descriptor, *documentMultikeyPaths); wuow.commit(); }); diff --git a/src/mongo/db/catalog/validate_state.h b/src/mongo/db/catalog/validate_state.h index 396f3393399..4cf713c908b 100644 --- a/src/mongo/db/catalog/validate_state.h +++ b/src/mongo/db/catalog/validate_state.h @@ -100,7 +100,7 @@ public: return _database; } - Collection* getCollection() const { + const Collection* getCollection() const { invariant(_collection); return _collection; } @@ -204,7 +204,7 @@ private: boost::optional<Lock::CollectionLock> _collectionLock; Database* _database; - Collection* _collection; + const Collection* _collection; // Stores the indexes that are going to be validated. When validate yields periodically we'll // use this list to determine if validation should abort when an existing index that was diff --git a/src/mongo/db/catalog/validate_state_test.cpp b/src/mongo/db/catalog/validate_state_test.cpp index e7f1e7a5111..bcd94aa94ad 100644 --- a/src/mongo/db/catalog/validate_state_test.cpp +++ b/src/mongo/db/catalog/validate_state_test.cpp @@ -63,7 +63,8 @@ public: /** * Create collection 'nss' and insert some documents. It will possess a default _id index. */ - Collection* createCollectionAndPopulateIt(OperationContext* opCtx, const NamespaceString& nss); + const Collection* createCollectionAndPopulateIt(OperationContext* opCtx, + const NamespaceString& nss); private: void setUp() override; @@ -75,13 +76,13 @@ void ValidateStateTest::createCollection(OperationContext* opCtx, const Namespac ASSERT_OK(storageInterface()->createCollection(opCtx, nss, defaultCollectionOptions)); } -Collection* ValidateStateTest::createCollectionAndPopulateIt(OperationContext* opCtx, - const NamespaceString& nss) { +const Collection* ValidateStateTest::createCollectionAndPopulateIt(OperationContext* opCtx, + const NamespaceString& nss) { // Create collection. createCollection(opCtx, nss); AutoGetCollection autoColl(opCtx, nss, MODE_X); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); invariant(collection); // Insert some data. @@ -141,14 +142,14 @@ void createIndex(OperationContext* opCtx, const NamespaceString& nss, const BSON * Drops index 'indexName' in collection 'nss'. */ void dropIndex(OperationContext* opCtx, const NamespaceString& nss, const std::string& indexName) { - AutoGetCollection autoColl(opCtx, nss, MODE_X); + AutoGetCollection collection(opCtx, nss, MODE_X); WriteUnitOfWork wuow(opCtx); - auto collection = autoColl.getCollection(); auto indexDescriptor = collection->getIndexCatalog()->findIndexByName(opCtx, indexName); ASSERT(indexDescriptor); - ASSERT_OK(collection->getIndexCatalog()->dropIndex(opCtx, indexDescriptor)); + ASSERT_OK( + collection.getWritableCollection()->getIndexCatalog()->dropIndex(opCtx, indexDescriptor)); wuow.commit(); } diff --git a/src/mongo/db/catalog_raii.h b/src/mongo/db/catalog_raii.h index c8d5f017a3b..47444538dd5 100644 --- a/src/mongo/db/catalog_raii.h +++ b/src/mongo/db/catalog_raii.h @@ -116,6 +116,24 @@ public: AutoGetCollectionViewMode viewMode = AutoGetCollectionViewMode::kViewsForbidden, Date_t deadline = Date_t::max()); + explicit operator bool() const { + return static_cast<bool>(_coll); + } + + /** + * AutoGetCollection can be used as a pointer with the -> operator. + */ + CollectionPtr operator->() const { + return getCollection(); + } + + /** + * Dereference operator, returns a lvalue reference to the collection. + */ + std::add_lvalue_reference_t<std::remove_pointer_t<CollectionPtr>> operator*() const { + return *getCollection(); + } + /** * Returns the database, or nullptr if it didn't exist. */ @@ -167,8 +185,8 @@ private: }; struct CatalogCollectionLookup { - using CollectionStorage = Collection*; - using CollectionPtr = Collection*; + using CollectionStorage = const Collection*; + using CollectionPtr = const Collection*; static CollectionStorage lookupCollection(OperationContext* opCtx, const NamespaceString& nss); static CollectionPtr toCollectionPtr(CollectionStorage collection) { @@ -188,6 +206,14 @@ struct CatalogCollectionLookupForRead { class AutoGetCollection : public AutoGetCollectionBase<CatalogCollectionLookup> { public: using AutoGetCollectionBase::AutoGetCollectionBase; + + /** + * Returns writable Collection. Necessary Collection lock mode is required. + * Any previous Collection that has been returned may be invalidated. + */ + Collection* getWritableCollection() const { + return const_cast<Collection*>(getCollection()); + } }; /** @@ -310,7 +336,7 @@ public: /** * Returns a pointer to the oplog collection or nullptr if the oplog collection didn't exist. */ - Collection* getCollection() const { + const Collection* getCollection() const { return _oplog; } @@ -321,7 +347,7 @@ private: boost::optional<Lock::DBLock> _dbWriteLock; boost::optional<Lock::CollectionLock> _collWriteLock; repl::LocalOplogInfo* _oplogInfo; - Collection* _oplog; + const Collection* _oplog; }; } // namespace mongo diff --git a/src/mongo/db/cloner.cpp b/src/mongo/db/cloner.cpp index 19f1e8efd41..4d445043f6c 100644 --- a/src/mongo/db/cloner.cpp +++ b/src/mongo/db/cloner.cpp @@ -367,7 +367,7 @@ Status Cloner::_createCollectionsForDb( opCtx->checkForInterrupt(); WriteUnitOfWork wunit(opCtx); - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); if (collection) { if (!params.shardedColl) { diff --git a/src/mongo/db/commands/dbhash.cpp b/src/mongo/db/commands/dbhash.cpp index b8e627fa6b3..ad150d7c116 100644 --- a/src/mongo/db/commands/dbhash.cpp +++ b/src/mongo/db/commands/dbhash.cpp @@ -316,7 +316,7 @@ public: private: std::string _hashCollection(OperationContext* opCtx, Database* db, const NamespaceString& nss) { - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); invariant(collection); diff --git a/src/mongo/db/commands/drop_indexes.cpp b/src/mongo/db/commands/drop_indexes.cpp index cb6cc68f5f5..5252df3c66f 100644 --- a/src/mongo/db/commands/drop_indexes.cpp +++ b/src/mongo/db/commands/drop_indexes.cpp @@ -145,10 +145,9 @@ public: << toReIndexNss << "' while replication is active"); } - AutoGetCollection autoColl(opCtx, toReIndexNss, MODE_X); - Collection* collection = autoColl.getCollection(); + AutoGetCollection collection(opCtx, toReIndexNss, MODE_X); if (!collection) { - auto db = autoColl.getDb(); + auto db = collection.getDb(); if (db && ViewCatalog::get(db)->lookup(opCtx, toReIndexNss.ns())) uasserted(ErrorCodes::CommandNotSupportedOnView, "can't re-index a view"); else @@ -220,17 +219,18 @@ public: writeConflictRetry(opCtx, "dropAllIndexes", toReIndexNss.ns(), [&] { WriteUnitOfWork wunit(opCtx); - collection->getIndexCatalog()->dropAllIndexes(opCtx, true); + collection.getWritableCollection()->getIndexCatalog()->dropAllIndexes(opCtx, true); - swIndexesToRebuild = - indexer->init(opCtx, collection, all, MultiIndexBlock::kNoopOnInitFn); + swIndexesToRebuild = indexer->init( + opCtx, collection.getWritableCollection(), all, MultiIndexBlock::kNoopOnInitFn); uassertStatusOK(swIndexesToRebuild.getStatus()); wunit.commit(); }); // The 'indexer' can throw, so ensure build cleanup occurs. auto abortOnExit = makeGuard([&] { - indexer->abortIndexBuild(opCtx, collection, MultiIndexBlock::kNoopOnCleanUpFn); + indexer->abortIndexBuild( + opCtx, collection.getWritableCollection(), MultiIndexBlock::kNoopOnCleanUpFn); }); if (MONGO_unlikely(reIndexCrashAfterDrop.shouldFail())) { @@ -240,14 +240,15 @@ public: // The following function performs its own WriteConflict handling, so don't wrap it in a // writeConflictRetry loop. - uassertStatusOK(indexer->insertAllDocumentsInCollection(opCtx, collection)); + uassertStatusOK( + indexer->insertAllDocumentsInCollection(opCtx, collection.getWritableCollection())); uassertStatusOK(indexer->checkConstraints(opCtx)); writeConflictRetry(opCtx, "commitReIndex", toReIndexNss.ns(), [&] { WriteUnitOfWork wunit(opCtx); uassertStatusOK(indexer->commit(opCtx, - collection, + collection.getWritableCollection(), MultiIndexBlock::kNoopOnCreateEachFn, MultiIndexBlock::kNoopOnCommitFn)); wunit.commit(); @@ -259,7 +260,7 @@ public: // tries to read in the intermediate state where all indexes are newer than the current // snapshot so are unable to be used. auto clusterTime = LogicalClock::getClusterTimeForReplicaSet(opCtx).asTimestamp(); - collection->setMinimumVisibleSnapshot(clusterTime); + collection.getWritableCollection()->setMinimumVisibleSnapshot(clusterTime); result.append("nIndexes", static_cast<int>(swIndexesToRebuild.getValue().size())); result.append("indexes", swIndexesToRebuild.getValue()); diff --git a/src/mongo/db/commands/find_and_modify.cpp b/src/mongo/db/commands/find_and_modify.cpp index f944274c695..161e44d6dbd 100644 --- a/src/mongo/db/commands/find_and_modify.cpp +++ b/src/mongo/db/commands/find_and_modify.cpp @@ -203,7 +203,7 @@ void recordStatsForTopCommand(OperationContext* opCtx) { curOp->getReadWriteType()); } -void checkIfTransactionOnCappedColl(Collection* coll, bool inTransaction) { +void checkIfTransactionOnCappedColl(const Collection* coll, bool inTransaction) { if (coll && coll->isCapped()) { uassert( ErrorCodes::OperationNotSupportedInTransaction, @@ -285,7 +285,7 @@ public: CollectionShardingState::get(opCtx, nsString)->checkShardVersionOrThrow(opCtx); - Collection* const collection = autoColl.getCollection(); + const Collection* const collection = autoColl.getCollection(); const auto exec = uassertStatusOK(getExecutorDelete(opDebug, collection, &parsedDelete, verbosity)); @@ -310,7 +310,7 @@ public: CollectionShardingState::get(opCtx, nsString)->checkShardVersionOrThrow(opCtx); - Collection* const collection = autoColl.getCollection(); + const Collection* const collection = autoColl.getCollection(); const auto exec = uassertStatusOK(getExecutorUpdate(opDebug, collection, &parsedUpdate, verbosity)); @@ -468,7 +468,7 @@ public: assertCanWrite(opCtx, nsString); - Collection* const collection = autoColl.getCollection(); + const Collection* const collection = autoColl.getCollection(); checkIfTransactionOnCappedColl(collection, inTransaction); const auto exec = uassertStatusOK( @@ -524,7 +524,7 @@ public: assertCanWrite(opCtx, nsString); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); // Create the collection if it does not exist when performing an upsert because the // update stage does not create its own collection diff --git a/src/mongo/db/commands/list_collections.cpp b/src/mongo/db/commands/list_collections.cpp index 77a79629d61..d080f8313db 100644 --- a/src/mongo/db/commands/list_collections.cpp +++ b/src/mongo/db/commands/list_collections.cpp @@ -317,7 +317,7 @@ public: } Lock::CollectionLock clk(opCtx, nss, MODE_IS); - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); BSONObj collBson = buildCollectionBson(opCtx, collection, includePendingDrops, nameOnly); diff --git a/src/mongo/db/commands/mr_test.cpp b/src/mongo/db/commands/mr_test.cpp index 2199c17daa9..f6af27117eb 100644 --- a/src/mongo/db/commands/mr_test.cpp +++ b/src/mongo/db/commands/mr_test.cpp @@ -267,7 +267,7 @@ public: * Tracks the temporary collections mapReduces creates. */ void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, @@ -321,7 +321,7 @@ void MapReduceOpObserver::onInserts(OperationContext* opCtx, } void MapReduceOpObserver::onCreateCollection(OperationContext*, - Collection*, + const Collection*, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj&, @@ -530,14 +530,14 @@ TEST_F(MapReduceCommandTest, ReplacingExistingOutputCollectionPreservesIndexes) auto indexSpec = BSON("v" << 2 << "key" << BSON("a" << 1) << "name" << "a_1"); { - AutoGetCollection autoColl(_opCtx.get(), outputNss, MODE_X); - auto coll = autoColl.getCollection(); + AutoGetCollection coll(_opCtx.get(), outputNss, MODE_X); ASSERT(coll); - auto indexCatalog = coll->getIndexCatalog(); writeConflictRetry( _opCtx.get(), "ReplacingExistingOutputCollectionPreservesIndexes", outputNss.ns(), [&] { WriteUnitOfWork wuow(_opCtx.get()); - ASSERT_OK(indexCatalog->createIndexOnEmptyCollection(_opCtx.get(), indexSpec)); + ASSERT_OK( + coll.getWritableCollection()->getIndexCatalog()->createIndexOnEmptyCollection( + _opCtx.get(), indexSpec)); wuow.commit(); }); } diff --git a/src/mongo/db/commands/resize_oplog.cpp b/src/mongo/db/commands/resize_oplog.cpp index b7d88507f66..1fb1c022ee2 100644 --- a/src/mongo/db/commands/resize_oplog.cpp +++ b/src/mongo/db/commands/resize_oplog.cpp @@ -83,10 +83,9 @@ public: const std::string& dbname, const BSONObj& jsobj, BSONObjBuilder& result) { - AutoGetCollection autoColl(opCtx, NamespaceString::kRsOplogNamespace, MODE_X); - Database* database = autoColl.getDb(); + AutoGetCollection coll(opCtx, NamespaceString::kRsOplogNamespace, MODE_X); + Database* database = coll.getDb(); uassert(ErrorCodes::NamespaceNotFound, "database local does not exist", database); - Collection* coll = autoColl.getCollection(); uassert(ErrorCodes::NamespaceNotFound, "oplog does not exist", coll); uassert(ErrorCodes::IllegalOperation, "oplog isn't capped", coll->isCapped()); diff --git a/src/mongo/db/commands/test_commands.cpp b/src/mongo/db/commands/test_commands.cpp index 397bb7188fd..c3585082655 100644 --- a/src/mongo/db/commands/test_commands.cpp +++ b/src/mongo/db/commands/test_commands.cpp @@ -92,7 +92,7 @@ public: WriteUnitOfWork wunit(opCtx); UnreplicatedWritesBlock unreplicatedWritesBlock(opCtx); - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); if (!collection) { collection = db->createCollection(opCtx, nss); @@ -146,7 +146,7 @@ public: // Lock the database in mode IX and lock the collection exclusively. AutoGetCollection autoColl(opCtx, fullNs, MODE_X); - Collection* collection = autoColl.getCollection(); + Collection* collection = autoColl.getWritableCollection(); if (!collection) { uasserted(ErrorCodes::NamespaceNotFound, str::stream() << "collection " << fullNs.ns() << " does not exist"); diff --git a/src/mongo/db/concurrency/deferred_writer.cpp b/src/mongo/db/concurrency/deferred_writer.cpp index f533a22dfe9..3883ae2cd40 100644 --- a/src/mongo/db/concurrency/deferred_writer.cpp +++ b/src/mongo/db/concurrency/deferred_writer.cpp @@ -112,7 +112,7 @@ void DeferredWriter::_worker(InsertStatement stmt) { auto agc = std::move(result.getValue()); - Collection& collection = *agc->getCollection(); + const Collection& collection = *agc->getCollection(); Status status = writeConflictRetry(opCtx, "deferred insert", _nss.ns(), [&] { WriteUnitOfWork wuow(opCtx); diff --git a/src/mongo/db/dbhelpers.cpp b/src/mongo/db/dbhelpers.cpp index 36b034e0b05..29e2ce7f289 100644 --- a/src/mongo/db/dbhelpers.cpp +++ b/src/mongo/db/dbhelpers.cpp @@ -130,7 +130,7 @@ bool Helpers::findById(OperationContext* opCtx, invariant(database); // TODO ForRead? - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, NamespaceString(ns)); if (!collection) { return false; @@ -139,7 +139,7 @@ bool Helpers::findById(OperationContext* opCtx, if (nsFound) *nsFound = true; - IndexCatalog* catalog = collection->getIndexCatalog(); + const IndexCatalog* catalog = collection->getIndexCatalog(); const IndexDescriptor* desc = catalog->findIdIndex(opCtx); if (!desc) @@ -287,7 +287,7 @@ BSONObj Helpers::inferKeyPattern(const BSONObj& o) { void Helpers::emptyCollection(OperationContext* opCtx, const NamespaceString& nss) { OldClientContext context(opCtx, nss.ns()); repl::UnreplicatedWritesBlock uwb(opCtx); - Collection* collection = context.db() + const Collection* collection = context.db() ? CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss) : nullptr; deleteObjects(opCtx, collection, nss, BSONObj(), false); diff --git a/src/mongo/db/exec/delete.cpp b/src/mongo/db/exec/delete.cpp index 78528e74b0e..456e1be27e6 100644 --- a/src/mongo/db/exec/delete.cpp +++ b/src/mongo/db/exec/delete.cpp @@ -71,7 +71,7 @@ bool shouldRestartDeleteIfNoLongerMatches(const DeleteStageParams* params) { DeleteStage::DeleteStage(ExpressionContext* expCtx, std::unique_ptr<DeleteStageParams> params, WorkingSet* ws, - Collection* collection, + const Collection* collection, PlanStage* child) : RequiresMutableCollectionStage(kStageType.rawData(), expCtx, collection), _params(std::move(params)), diff --git a/src/mongo/db/exec/delete.h b/src/mongo/db/exec/delete.h index 813ff1683fb..0123902e508 100644 --- a/src/mongo/db/exec/delete.h +++ b/src/mongo/db/exec/delete.h @@ -104,7 +104,7 @@ public: DeleteStage(ExpressionContext* expCtx, std::unique_ptr<DeleteStageParams> params, WorkingSet* ws, - Collection* collection, + const Collection* collection, PlanStage* child); bool isEOF() final; diff --git a/src/mongo/db/exec/requires_collection_stage.cpp b/src/mongo/db/exec/requires_collection_stage.cpp index 59f41a27e53..92a4a1e0279 100644 --- a/src/mongo/db/exec/requires_collection_stage.cpp +++ b/src/mongo/db/exec/requires_collection_stage.cpp @@ -33,16 +33,14 @@ namespace mongo { -template <typename CollectionT> -void RequiresCollectionStageBase<CollectionT>::doSaveState() { +void RequiresCollectionStage::doSaveState() { doSaveStateRequiresCollection(); // A stage may not access storage while in a saved state. _collection = nullptr; } -template <typename CollectionT> -void RequiresCollectionStageBase<CollectionT>::doRestoreState() { +void RequiresCollectionStage::doRestoreState() { invariant(!_collection); // We should be holding a lock associated with the name of the collection prior to yielding, @@ -76,7 +74,4 @@ void RequiresCollectionStageBase<CollectionT>::doRestoreState() { doRestoreStateRequiresCollection(); } -template class RequiresCollectionStageBase<const Collection*>; -template class RequiresCollectionStageBase<Collection*>; - } // namespace mongo diff --git a/src/mongo/db/exec/requires_collection_stage.h b/src/mongo/db/exec/requires_collection_stage.h index 648cd0aa927..eb9498f5e04 100644 --- a/src/mongo/db/exec/requires_collection_stage.h +++ b/src/mongo/db/exec/requires_collection_stage.h @@ -39,24 +39,19 @@ namespace mongo { /** - * A base class for plan stages which access a collection. In addition to providing derived classes + * A class for plan stages which access a collection. In addition to providing derived classes * access to the Collection pointer, the primary purpose of this class is to assume responsibility * for checking that the collection is still valid (e.g. has not been dropped) when recovering from * yield. * * Subclasses must implement doSaveStateRequiresCollection() and doRestoreStateRequiresCollection() * in order to supply custom yield preparation or yield recovery logic. - * - * Templated on 'CollectionT', which may be instantiated using either Collection* or const - * Collection*. This abstracts the implementation of this base class for use by derived classes - * which read (e.g. COLLSCAN and MULTI_ITERATOR) and derived classes that write (e.g. UPDATE and - * DELETE). Derived classes should use the 'RequiresCollectionStage' or - * 'RequiresMutableCollectionStage' aliases provided below. */ -template <typename CollectionT> -class RequiresCollectionStageBase : public PlanStage { +class RequiresCollectionStage : public PlanStage { public: - RequiresCollectionStageBase(const char* stageType, ExpressionContext* expCtx, CollectionT coll) + RequiresCollectionStage(const char* stageType, + ExpressionContext* expCtx, + const Collection* coll) : PlanStage(stageType, expCtx), _collection(coll), _collectionUUID(_collection->uuid()), @@ -65,7 +60,7 @@ public: invariant(_collection); } - virtual ~RequiresCollectionStageBase() = default; + virtual ~RequiresCollectionStage() = default; protected: void doSaveState() final; @@ -82,7 +77,7 @@ protected: */ virtual void doRestoreStateRequiresCollection() = 0; - CollectionT collection() const { + const Collection* collection() const { return _collection; } @@ -96,7 +91,7 @@ private: return CollectionCatalog::get(opCtx()).getEpoch(); } - CollectionT _collection; + const Collection* _collection; const UUID _collectionUUID; const uint64_t _catalogEpoch; @@ -105,10 +100,7 @@ private: const NamespaceString _nss; }; -// Type alias for use by PlanStages that read a Collection. -using RequiresCollectionStage = RequiresCollectionStageBase<const Collection*>; - // Type alias for use by PlanStages that write to a Collection. -using RequiresMutableCollectionStage = RequiresCollectionStageBase<Collection*>; +using RequiresMutableCollectionStage = RequiresCollectionStage; } // namespace mongo diff --git a/src/mongo/db/exec/requires_index_stage.h b/src/mongo/db/exec/requires_index_stage.h index f8e1e7a3b88..cd3ba14fe4e 100644 --- a/src/mongo/db/exec/requires_index_stage.h +++ b/src/mongo/db/exec/requires_index_stage.h @@ -37,9 +37,9 @@ namespace mongo { /** * A base class for plan stages which require access to a particular index within a particular - * collection. Provides subclasses access to the index's Collection*, as well as to catalog types - * representing the index itself such as the IndexDescriptor. This base class is responsible for - * checking that the collection and index are still valid (e.g. have not been dropped) when + * collection. Provides subclasses access to the index's const Collection*, as well as to catalog + * types representing the index itself such as the IndexDescriptor. This base class is responsible + * for checking that the collection and index are still valid (e.g. have not been dropped) when * recovering from yield. * * Subclasses must implement doSaveStateRequiresIndex() and doRestoreStateRequiresIndex() in order diff --git a/src/mongo/db/exec/stagedebug_cmd.cpp b/src/mongo/db/exec/stagedebug_cmd.cpp index e07930d549a..06dd3532fdc 100644 --- a/src/mongo/db/exec/stagedebug_cmd.cpp +++ b/src/mongo/db/exec/stagedebug_cmd.cpp @@ -148,14 +148,14 @@ public: auto expCtx = make_intrusive<ExpressionContext>( opCtx, std::unique_ptr<CollatorInterface>(nullptr), nss); - // Need a context to get the actual Collection* + // Need a context to get the actual const Collection* // TODO A write lock is currently taken here to accommodate stages that perform writes // (e.g. DeleteStage). This should be changed to use a read lock for read-only // execution trees. AutoGetCollection autoColl(opCtx, nss, MODE_IX); // Make sure the collection is valid. - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); uassert(ErrorCodes::NamespaceNotFound, str::stream() << "Couldn't find collection " << nss.ns(), collection); @@ -201,7 +201,7 @@ public: } PlanStage* parseQuery(const boost::intrusive_ptr<ExpressionContext>& expCtx, - Collection* collection, + const Collection* collection, BSONObj obj, WorkingSet* workingSet, const NamespaceString& nss, diff --git a/src/mongo/db/exec/update_stage.cpp b/src/mongo/db/exec/update_stage.cpp index 776f6aec134..3f0340c66b9 100644 --- a/src/mongo/db/exec/update_stage.cpp +++ b/src/mongo/db/exec/update_stage.cpp @@ -109,7 +109,7 @@ CollectionUpdateArgs::StoreDocOption getStoreDocMode(const UpdateRequest& update UpdateStage::UpdateStage(ExpressionContext* expCtx, const UpdateStageParams& params, WorkingSet* ws, - Collection* collection, + const Collection* collection, PlanStage* child) : UpdateStage(expCtx, params, ws, collection) { // We should never reach here if the request is an upsert. @@ -121,7 +121,7 @@ UpdateStage::UpdateStage(ExpressionContext* expCtx, UpdateStage::UpdateStage(ExpressionContext* expCtx, const UpdateStageParams& params, WorkingSet* ws, - Collection* collection) + const Collection* collection) : RequiresMutableCollectionStage(kStageType.rawData(), expCtx, collection), _params(params), _ws(ws), diff --git a/src/mongo/db/exec/update_stage.h b/src/mongo/db/exec/update_stage.h index 0eff229ce7d..7fc304f776c 100644 --- a/src/mongo/db/exec/update_stage.h +++ b/src/mongo/db/exec/update_stage.h @@ -86,7 +86,7 @@ public: UpdateStage(ExpressionContext* expCtx, const UpdateStageParams& params, WorkingSet* ws, - Collection* collection, + const Collection* collection, PlanStage* child); bool isEOF() override; @@ -104,7 +104,7 @@ protected: UpdateStage(ExpressionContext* expCtx, const UpdateStageParams& params, WorkingSet* ws, - Collection* collection); + const Collection* collection); void doSaveStateRequiresCollection() final {} diff --git a/src/mongo/db/exec/upsert_stage.cpp b/src/mongo/db/exec/upsert_stage.cpp index a0fd31ca201..906b99e679a 100644 --- a/src/mongo/db/exec/upsert_stage.cpp +++ b/src/mongo/db/exec/upsert_stage.cpp @@ -51,7 +51,7 @@ const FieldRef idFieldRef(idFieldName); UpsertStage::UpsertStage(ExpressionContext* expCtx, const UpdateStageParams& params, WorkingSet* ws, - Collection* collection, + const Collection* collection, PlanStage* child) : UpdateStage(expCtx, params, ws, collection) { // We should never create this stage for a non-upsert request. diff --git a/src/mongo/db/exec/upsert_stage.h b/src/mongo/db/exec/upsert_stage.h index 163ad826470..7735d5b996b 100644 --- a/src/mongo/db/exec/upsert_stage.h +++ b/src/mongo/db/exec/upsert_stage.h @@ -54,7 +54,7 @@ public: UpsertStage(ExpressionContext* expCtx, const UpdateStageParams& params, WorkingSet* ws, - Collection* collection, + const Collection* collection, PlanStage* child); bool isEOF() final; diff --git a/src/mongo/db/fcv_op_observer.h b/src/mongo/db/fcv_op_observer.h index 93c4d0b7bab..374c4387dc1 100644 --- a/src/mongo/db/fcv_op_observer.h +++ b/src/mongo/db/fcv_op_observer.h @@ -112,7 +112,7 @@ public: const boost::optional<repl::OpTime> prevWriteOpTimeInTransaction, const boost::optional<OplogSlot> slot) final {} void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/free_mon/free_mon_op_observer.h b/src/mongo/db/free_mon/free_mon_op_observer.h index f06efef564f..34496b448c9 100644 --- a/src/mongo/db/free_mon/free_mon_op_observer.h +++ b/src/mongo/db/free_mon/free_mon_op_observer.h @@ -106,7 +106,7 @@ public: const boost::optional<OplogSlot> slot) final{}; void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/index/index_access_method.cpp b/src/mongo/db/index/index_access_method.cpp index c2a07973796..4047fb9f705 100644 --- a/src/mongo/db/index/index_access_method.cpp +++ b/src/mongo/db/index/index_access_method.cpp @@ -387,7 +387,7 @@ void AbstractIndexAccessMethod::prepareUpdate(OperationContext* opCtx, } Status AbstractIndexAccessMethod::update(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const UpdateTicket& ticket, int64_t* numInserted, int64_t* numDeleted) { @@ -725,7 +725,7 @@ Status AbstractIndexAccessMethod::commitBulk(OperationContext* opCtx, } void AbstractIndexAccessMethod::setIndexIsMultikey(OperationContext* opCtx, - Collection* collection, + const Collection* collection, MultikeyPaths paths) { _indexCatalogEntry->setMultikey(opCtx, collection, paths); } diff --git a/src/mongo/db/index/index_access_method.h b/src/mongo/db/index/index_access_method.h index c2c3c1e47ca..4c1229c5335 100644 --- a/src/mongo/db/index/index_access_method.h +++ b/src/mongo/db/index/index_access_method.h @@ -138,7 +138,7 @@ public: * 'numDeleted' will be set to the number of keys removed from the index for the document. */ virtual Status update(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const UpdateTicket& ticket, int64_t* numInserted, int64_t* numDeleted) = 0; @@ -198,7 +198,7 @@ public: * Sets this index as multikey with the provided paths. */ virtual void setIndexIsMultikey(OperationContext* opCtx, - Collection* collection, + const Collection* collection, MultikeyPaths paths) = 0; // @@ -473,7 +473,7 @@ public: UpdateTicket* ticket) const final; Status update(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const UpdateTicket& ticket, int64_t* numInserted, int64_t* numDeleted) final; @@ -499,7 +499,7 @@ public: Status compact(OperationContext* opCtx) final; void setIndexIsMultikey(OperationContext* opCtx, - Collection* collection, + const Collection* collection, MultikeyPaths paths) final; std::unique_ptr<BulkBuilder> initiateBulk( diff --git a/src/mongo/db/index/index_descriptor.cpp b/src/mongo/db/index/index_descriptor.cpp index 465ed4729be..f998864355e 100644 --- a/src/mongo/db/index/index_descriptor.cpp +++ b/src/mongo/db/index/index_descriptor.cpp @@ -99,7 +99,7 @@ constexpr StringData IndexDescriptor::kUniqueFieldName; constexpr StringData IndexDescriptor::kHiddenFieldName; constexpr StringData IndexDescriptor::kWeightsFieldName; -IndexDescriptor::IndexDescriptor(Collection* collection, +IndexDescriptor::IndexDescriptor(const Collection* collection, const std::string& accessMethodName, BSONObj infoObj) : _accessMethodName(accessMethodName), diff --git a/src/mongo/db/index/index_descriptor.h b/src/mongo/db/index/index_descriptor.h index fee07610272..b4710c8e4b8 100644 --- a/src/mongo/db/index/index_descriptor.h +++ b/src/mongo/db/index/index_descriptor.h @@ -95,7 +95,9 @@ public: /** * infoObj is a copy of the index-describing BSONObj contained in the catalog. */ - IndexDescriptor(Collection* collection, const std::string& accessMethodName, BSONObj infoObj); + IndexDescriptor(const Collection* collection, + const std::string& accessMethodName, + BSONObj infoObj); /** * Returns true if the specified index version is supported, and returns false otherwise. diff --git a/src/mongo/db/index_build_entry_helpers.cpp b/src/mongo/db/index_build_entry_helpers.cpp index f537d445003..da3f43b29e2 100644 --- a/src/mongo/db/index_build_entry_helpers.cpp +++ b/src/mongo/db/index_build_entry_helpers.cpp @@ -62,7 +62,7 @@ Status upsert(OperationContext* opCtx, const IndexBuildEntry& indexBuildEntry) { [&]() -> Status { AutoGetCollection autoCollection( opCtx, NamespaceString::kIndexBuildEntryNamespace, MODE_IX); - Collection* collection = autoCollection.getCollection(); + const Collection* collection = autoCollection.getCollection(); if (!collection) { str::stream ss; ss << "Collection not found: " @@ -118,7 +118,7 @@ Status upsert(OperationContext* opCtx, const BSONObj& filter, const BSONObj& upd [&]() -> Status { AutoGetCollection autoCollection( opCtx, NamespaceString::kIndexBuildEntryNamespace, MODE_IX); - Collection* collection = autoCollection.getCollection(); + const Collection* collection = autoCollection.getCollection(); if (!collection) { str::stream ss; ss << "Collection not found: " @@ -158,7 +158,7 @@ void ensureIndexBuildEntriesNamespaceExists(OperationContext* opCtx) { opCtx, NamespaceString::kIndexBuildEntryNamespace)) { WriteUnitOfWork wuow(opCtx); CollectionOptions defaultCollectionOptions; - Collection* collection = + const Collection* collection = db->createCollection(opCtx, NamespaceString::kIndexBuildEntryNamespace, defaultCollectionOptions); @@ -195,7 +195,7 @@ Status addIndexBuildEntry(OperationContext* opCtx, const IndexBuildEntry& indexB [&]() -> Status { AutoGetCollection autoCollection( opCtx, NamespaceString::kIndexBuildEntryNamespace, MODE_IX); - Collection* collection = autoCollection.getCollection(); + const Collection* collection = autoCollection.getCollection(); if (!collection) { str::stream ss; ss << "Collection not found: " << NamespaceString::kIndexBuildEntryNamespace.ns(); @@ -229,7 +229,7 @@ Status removeIndexBuildEntry(OperationContext* opCtx, UUID indexBuildUUID) { [&]() -> Status { AutoGetCollection autoCollection( opCtx, NamespaceString::kIndexBuildEntryNamespace, MODE_IX); - Collection* collection = autoCollection.getCollection(); + const Collection* collection = autoCollection.getCollection(); if (!collection) { str::stream ss; ss << "Collection not found: " << NamespaceString::kIndexBuildEntryNamespace.ns(); diff --git a/src/mongo/db/index_builds_coordinator.cpp b/src/mongo/db/index_builds_coordinator.cpp index 1832e2c7bb7..46ab4fc2191 100644 --- a/src/mongo/db/index_builds_coordinator.cpp +++ b/src/mongo/db/index_builds_coordinator.cpp @@ -118,7 +118,7 @@ void checkShardKeyRestrictions(OperationContext* opCtx, * bypass the index build registration. */ bool shouldBuildIndexesOnEmptyCollectionSinglePhased(OperationContext* opCtx, - Collection* collection, + const Collection* collection, IndexBuildProtocol protocol) { const auto& nss = collection->ns(); invariant(opCtx->lockState()->isCollectionLockedForMode(nss, MODE_X), str::stream() << nss); @@ -500,7 +500,8 @@ StatusWith<std::pair<long long, long long>> IndexBuildsCoordinator::rebuildIndex } auto& collectionCatalog = CollectionCatalog::get(opCtx->getServiceContext()); - Collection* collection = collectionCatalog.lookupCollectionByNamespace(opCtx, nss); + Collection* collection = + collectionCatalog.lookupCollectionByNamespaceForMetadataWrite(opCtx, nss); // Complete the index build. return _runIndexRebuildForRecovery(opCtx, collection, buildUUID, repair); @@ -526,7 +527,8 @@ Status IndexBuildsCoordinator::_startIndexBuildForRecovery(OperationContext* opC } auto& collectionCatalog = CollectionCatalog::get(opCtx->getServiceContext()); - Collection* collection = collectionCatalog.lookupCollectionByNamespace(opCtx, nss); + Collection* collection = + collectionCatalog.lookupCollectionByNamespaceForMetadataWrite(opCtx, nss); auto indexCatalog = collection->getIndexCatalog(); { // These steps are combined into a single WUOW to ensure there are no commits without @@ -647,8 +649,8 @@ Status IndexBuildsCoordinator::_setUpResumeIndexBuild(OperationContext* opCtx, Lock::CollectionLock collLock(opCtx, nssOrUuid, MODE_X); auto& collectionCatalog = CollectionCatalog::get(opCtx->getServiceContext()); - auto collection = - collectionCatalog.lookupCollectionByUUID(opCtx, resumeInfo.getCollectionUUID()); + auto collection = collectionCatalog.lookupCollectionByUUIDForMetadataWrite( + opCtx, resumeInfo.getCollectionUUID()); invariant(collection); auto durableCatalog = DurableCatalog::get(opCtx); @@ -877,12 +879,11 @@ void IndexBuildsCoordinator::applyStartIndexBuild(OperationContext* opCtx, writeConflictRetry(opCtx, "IndexBuildsCoordinator::applyStartIndexBuild", nss.ns(), [&] { WriteUnitOfWork wuow(opCtx); - AutoGetCollection autoColl(opCtx, dbAndUUID, MODE_X); - auto coll = autoColl.getCollection(); + AutoGetCollection coll(opCtx, dbAndUUID, MODE_X); invariant(coll, str::stream() << "Collection with UUID " << collUUID << " was dropped."); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + IndexCatalog* indexCatalog = coll.getWritableCollection()->getIndexCatalog(); const bool includeUnfinished = false; for (const auto& spec : oplogEntry.indexSpecs) { @@ -1315,8 +1316,8 @@ void IndexBuildsCoordinator::_completeAbort(OperationContext* opCtx, std::shared_ptr<ReplIndexBuildState> replState, IndexBuildAction signalAction, Status reason) { - auto coll = - CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, replState->collectionUUID); + auto coll = CollectionCatalog::get(opCtx).lookupCollectionByUUIDForMetadataWrite( + opCtx, replState->collectionUUID); const NamespaceStringOrUUID dbAndUUID(replState->dbName, replState->collectionUUID); auto nss = coll->ns(); auto replCoord = repl::ReplicationCoordinator::get(opCtx); @@ -1422,7 +1423,7 @@ void IndexBuildsCoordinator::_completeSelfAbort(OperationContext* opCtx, void IndexBuildsCoordinator::_completeAbortForShutdown( OperationContext* opCtx, std::shared_ptr<ReplIndexBuildState> replState, - Collection* collection) { + const Collection* collection) { // Leave it as-if kill -9 happened. Startup recovery will restart the index build. auto isResumable = !replState->lastOpTimeBeforeInterceptors.isNull(); _indexBuildsManager.abortIndexBuildWithoutCleanupForShutdown( @@ -1727,7 +1728,8 @@ void IndexBuildsCoordinator::createIndex(OperationContext* opCtx, const BSONObj& spec, IndexBuildsManager::IndexConstraints indexConstraints, bool fromMigrate) { - auto collection = CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, collectionUUID); + auto collection = + CollectionCatalog::get(opCtx).lookupCollectionByUUIDForMetadataWrite(opCtx, collectionUUID); invariant(collection, str::stream() << "IndexBuildsCoordinator::createIndexes: " << collectionUUID); auto nss = collection->ns(); @@ -1792,7 +1794,8 @@ void IndexBuildsCoordinator::createIndexesOnEmptyCollection(OperationContext* op UUID collectionUUID, const std::vector<BSONObj>& specs, bool fromMigrate) { - auto collection = CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, collectionUUID); + auto collection = + CollectionCatalog::get(opCtx).lookupCollectionByUUIDForMetadataWrite(opCtx, collectionUUID); invariant(collection, str::stream() << collectionUUID); invariant(collection->isEmpty(opCtx), str::stream() << collectionUUID); @@ -1961,7 +1964,7 @@ IndexBuildsCoordinator::_filterSpecsAndRegisterBuild(OperationContext* opCtx, // AutoGetCollection throws an exception if it is unable to look up the collection by UUID. NamespaceStringOrUUID nssOrUuid{dbName.toString(), collectionUUID}; AutoGetCollection autoColl(opCtx, nssOrUuid, MODE_X); - auto collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); const auto& nss = collection->ns(); // Disallow index builds on drop-pending namespaces (system.drop.*) if we are primary. @@ -2047,15 +2050,12 @@ IndexBuildsCoordinator::PostSetupAction IndexBuildsCoordinator::_setUpIndexBuild const IndexBuildOptions& indexBuildOptions) { const NamespaceStringOrUUID nssOrUuid{replState->dbName, replState->collectionUUID}; - AutoGetCollection autoColl(opCtx, nssOrUuid, MODE_X); - - auto collection = autoColl.getCollection(); - const auto& nss = collection->ns(); - CollectionShardingState::get(opCtx, nss)->checkShardVersionOrThrow(opCtx); + AutoGetCollection collection(opCtx, nssOrUuid, MODE_X); + CollectionShardingState::get(opCtx, collection->ns())->checkShardVersionOrThrow(opCtx); auto replCoord = repl::ReplicationCoordinator::get(opCtx); - const bool replSetAndNotPrimary = - replCoord->getSettings().usingReplSets() && !replCoord->canAcceptWritesFor(opCtx, nss); + const bool replSetAndNotPrimary = replCoord->getSettings().usingReplSets() && + !replCoord->canAcceptWritesFor(opCtx, collection->ns()); // We will not have a start timestamp if we are newly a secondary (i.e. we started as // primary but there was a stepdown). We will be unable to timestamp the initial catalog write, @@ -2075,7 +2075,7 @@ IndexBuildsCoordinator::PostSetupAction IndexBuildsCoordinator::_setUpIndexBuild // writes a no-op just to generate an optime. onInitFn = [&](std::vector<BSONObj>& specs) { if (!(replCoord->getSettings().usingReplSets() && - replCoord->canAcceptWritesFor(opCtx, nss))) { + replCoord->canAcceptWritesFor(opCtx, collection->ns()))) { // Not primary. return Status::OK(); } @@ -2096,7 +2096,7 @@ IndexBuildsCoordinator::PostSetupAction IndexBuildsCoordinator::_setUpIndexBuild opCtx->getServiceContext()->getOpObserver()->onStartIndexBuild( opCtx, - nss, + collection->ns(), replState->collectionUUID, replState->buildUUID, replState->indexSpecs, @@ -2105,12 +2105,13 @@ IndexBuildsCoordinator::PostSetupAction IndexBuildsCoordinator::_setUpIndexBuild return Status::OK(); }; } else { - onInitFn = MultiIndexBlock::makeTimestampedIndexOnInitFn(opCtx, collection); + onInitFn = MultiIndexBlock::makeTimestampedIndexOnInitFn(opCtx, collection.getCollection()); } IndexBuildsManager::SetupOptions options; options.indexConstraints = - repl::ReplicationCoordinator::get(opCtx)->shouldRelaxIndexConstraints(opCtx, nss) + repl::ReplicationCoordinator::get(opCtx)->shouldRelaxIndexConstraints(opCtx, + collection->ns()) ? IndexBuildsManager::IndexConstraints::kRelax : IndexBuildsManager::IndexConstraints::kEnforce; options.protocol = replState->protocol; @@ -2119,8 +2120,12 @@ IndexBuildsCoordinator::PostSetupAction IndexBuildsCoordinator::_setUpIndexBuild if (!replSetAndNotPrimary) { // On standalones and primaries, call setUpIndexBuild(), which makes the initial catalog // write. On primaries, this replicates the startIndexBuild oplog entry. - uassertStatusOK(_indexBuildsManager.setUpIndexBuild( - opCtx, collection, replState->indexSpecs, replState->buildUUID, onInitFn, options)); + uassertStatusOK(_indexBuildsManager.setUpIndexBuild(opCtx, + collection.getWritableCollection(), + replState->indexSpecs, + replState->buildUUID, + onInitFn, + options)); } else { // If we are starting the index build as a secondary, we must suppress calls to write // our initial oplog entry in setUpIndexBuild(). @@ -2134,12 +2139,18 @@ IndexBuildsCoordinator::PostSetupAction IndexBuildsCoordinator::_setUpIndexBuild tsBlock.emplace(opCtx, startTimestamp); } - uassertStatusOK(_indexBuildsManager.setUpIndexBuild( - opCtx, collection, replState->indexSpecs, replState->buildUUID, onInitFn, options)); + uassertStatusOK(_indexBuildsManager.setUpIndexBuild(opCtx, + collection.getWritableCollection(), + replState->indexSpecs, + replState->buildUUID, + onInitFn, + options)); } } catch (DBException& ex) { - _indexBuildsManager.abortIndexBuild( - opCtx, collection, replState->buildUUID, MultiIndexBlock::kNoopOnCleanUpFn); + _indexBuildsManager.abortIndexBuild(opCtx, + collection.getWritableCollection(), + replState->buildUUID, + MultiIndexBlock::kNoopOnCleanUpFn); const auto& status = ex.toStatus(); if (status == ErrorCodes::IndexAlreadyExists || @@ -2294,7 +2305,7 @@ void runOnAlternateContext(OperationContext* opCtx, std::string name, Func func) void IndexBuildsCoordinator::_cleanUpSinglePhaseAfterFailure( OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::shared_ptr<ReplIndexBuildState> replState, const IndexBuildOptions& indexBuildOptions, const Status& status) { @@ -2322,7 +2333,7 @@ void IndexBuildsCoordinator::_cleanUpSinglePhaseAfterFailure( void IndexBuildsCoordinator::_cleanUpTwoPhaseAfterFailure( OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::shared_ptr<ReplIndexBuildState> replState, const IndexBuildOptions& indexBuildOptions, const Status& status) { @@ -2399,8 +2410,8 @@ void IndexBuildsCoordinator::_runIndexBuildInner( // dropped while the index build is still registered for the collection -- until abortIndexBuild // is called. The collection can be renamed, but it is OK for the name to be stale just for // logging purposes. - auto collection = - CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, replState->collectionUUID); + auto collection = CollectionCatalog::get(opCtx).lookupCollectionByUUIDForRead( + opCtx, replState->collectionUUID); invariant(collection, str::stream() << "Collection with UUID " << replState->collectionUUID << " should exist because an index build is in progress: " @@ -2423,11 +2434,12 @@ void IndexBuildsCoordinator::_runIndexBuildInner( status.isA<ErrorCategory::ShutdownError>(), str::stream() << "Unexpected error code during index build cleanup: " << status); if (IndexBuildProtocol::kSinglePhase == replState->protocol) { - _cleanUpSinglePhaseAfterFailure(opCtx, collection, replState, indexBuildOptions, status); + _cleanUpSinglePhaseAfterFailure( + opCtx, collection.get(), replState, indexBuildOptions, status); } else { invariant(IndexBuildProtocol::kTwoPhase == replState->protocol, str::stream() << replState->buildUUID); - _cleanUpTwoPhaseAfterFailure(opCtx, collection, replState, indexBuildOptions, status); + _cleanUpTwoPhaseAfterFailure(opCtx, collection.get(), replState, indexBuildOptions, status); } // Any error that escapes at this point is not fatal and can be handled by the caller. @@ -2743,8 +2755,8 @@ IndexBuildsCoordinator::CommitResult IndexBuildsCoordinator::_insertKeysFromSide } // The collection object should always exist while an index build is registered. - auto collection = - CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, replState->collectionUUID); + auto collection = CollectionCatalog::get(opCtx).lookupCollectionByUUIDForMetadataWrite( + opCtx, replState->collectionUUID); invariant(collection, str::stream() << "Collection not found after relocking. Index build: " << replState->buildUUID @@ -2991,7 +3003,8 @@ std::vector<std::shared_ptr<ReplIndexBuildState>> IndexBuildsCoordinator::_filte return indexBuilds; } -int IndexBuildsCoordinator::getNumIndexesTotal(OperationContext* opCtx, Collection* collection) { +int IndexBuildsCoordinator::getNumIndexesTotal(OperationContext* opCtx, + const Collection* collection) { invariant(collection); const auto& nss = collection->ns(); invariant(opCtx->lockState()->isLocked(), @@ -3006,7 +3019,7 @@ int IndexBuildsCoordinator::getNumIndexesTotal(OperationContext* opCtx, Collecti std::vector<BSONObj> IndexBuildsCoordinator::prepareSpecListForCreate( OperationContext* opCtx, - Collection* collection, + const Collection* collection, const NamespaceString& nss, const std::vector<BSONObj>& indexSpecs) { UncommittedCollections::get(opCtx).invariantHasExclusiveAccessToCollection(opCtx, diff --git a/src/mongo/db/index_builds_coordinator.h b/src/mongo/db/index_builds_coordinator.h index ead5e5e39b1..12e80653829 100644 --- a/src/mongo/db/index_builds_coordinator.h +++ b/src/mongo/db/index_builds_coordinator.h @@ -434,7 +434,7 @@ public: * This function throws on error. Expects caller to have exclusive access to `collection`. */ static std::vector<BSONObj> prepareSpecListForCreate(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const NamespaceString& nss, const std::vector<BSONObj>& indexSpecs); @@ -461,7 +461,7 @@ public: * * Expects a lock to be held by the caller, so that 'collection' is safe to use. */ - static int getNumIndexesTotal(OperationContext* opCtx, Collection* collection); + static int getNumIndexesTotal(OperationContext* opCtx, const Collection* collection); /** @@ -597,7 +597,7 @@ protected: * Cleans up a single-phase index build after a failure. */ void _cleanUpSinglePhaseAfterFailure(OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::shared_ptr<ReplIndexBuildState> replState, const IndexBuildOptions& indexBuildOptions, const Status& status); @@ -606,7 +606,7 @@ protected: * Cleans up a two-phase index build after a failure. */ void _cleanUpTwoPhaseAfterFailure(OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::shared_ptr<ReplIndexBuildState> replState, const IndexBuildOptions& indexBuildOptions, const Status& status); @@ -631,7 +631,7 @@ protected: Status reason); void _completeAbortForShutdown(OperationContext* opCtx, std::shared_ptr<ReplIndexBuildState> replState, - Collection* collection); + const Collection* collection); /** * Waits for the last optime before the interceptors were installed on the node to be majority diff --git a/src/mongo/db/introspect.cpp b/src/mongo/db/introspect.cpp index 41598963c5f..31749c46c96 100644 --- a/src/mongo/db/introspect.cpp +++ b/src/mongo/db/introspect.cpp @@ -160,7 +160,7 @@ void profile(OperationContext* opCtx, NetworkOp op) { EnforcePrepareConflictsBlock enforcePrepare(opCtx); uassertStatusOK(createProfileCollection(opCtx, db)); - Collection* const coll = + const Collection* const coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, dbProfilingNS); invariant(!opCtx->shouldParticipateInFlowControl()); @@ -190,7 +190,7 @@ Status createProfileCollection(OperationContext* opCtx, Database* db) { // collection creation would endlessly throw errors because the collection exists: must check // and see the collection exists in order to break free. return writeConflictRetry(opCtx, "createProfileCollection", dbProfilingNS.ns(), [&] { - Collection* const collection = + const Collection* const collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, dbProfilingNS); if (collection) { if (!collection->isCapped()) { diff --git a/src/mongo/db/matcher/expression_text.cpp b/src/mongo/db/matcher/expression_text.cpp index 429fba332fd..c2ea279d6b6 100644 --- a/src/mongo/db/matcher/expression_text.cpp +++ b/src/mongo/db/matcher/expression_text.cpp @@ -66,7 +66,7 @@ TextMatchExpression::TextMatchExpression(OperationContext* opCtx, << nss.ns() << "')", db); - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); uassert(ErrorCodes::IndexNotFound, diff --git a/src/mongo/db/mongod_main.cpp b/src/mongo/db/mongod_main.cpp index d1acb0010b3..048f1d2e871 100644 --- a/src/mongo/db/mongod_main.cpp +++ b/src/mongo/db/mongod_main.cpp @@ -254,7 +254,7 @@ void logStartup(OperationContext* opCtx) { Lock::GlobalWrite lk(opCtx); AutoGetOrCreateDb autoDb(opCtx, startupLogCollectionName.db(), mongo::MODE_X); Database* db = autoDb.getDb(); - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, startupLogCollectionName); WriteUnitOfWork wunit(opCtx); if (!collection) { diff --git a/src/mongo/db/op_observer.h b/src/mongo/db/op_observer.h index 51753376d88..49c4123049d 100644 --- a/src/mongo/db/op_observer.h +++ b/src/mongo/db/op_observer.h @@ -182,7 +182,7 @@ public: } virtual void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/op_observer_impl.cpp b/src/mongo/db/op_observer_impl.cpp index 2466d1244b1..85fe5eca421 100644 --- a/src/mongo/db/op_observer_impl.cpp +++ b/src/mongo/db/op_observer_impl.cpp @@ -667,7 +667,7 @@ void OpObserverImpl::onInternalOpMessage( } void OpObserverImpl::onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, @@ -739,7 +739,7 @@ void OpObserverImpl::onCollMod(OperationContext* opCtx, if (!db) { return; } - Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); + const Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); invariant(coll->uuid() == uuid); invariant(DurableCatalog::get(opCtx)->isEqualToMetadataUUID(opCtx, coll->getCatalogId(), uuid)); diff --git a/src/mongo/db/op_observer_impl.h b/src/mongo/db/op_observer_impl.h index 6e4a27110a4..fac5f4f62b4 100644 --- a/src/mongo/db/op_observer_impl.h +++ b/src/mongo/db/op_observer_impl.h @@ -112,7 +112,7 @@ public: const boost::optional<repl::OpTime> prevWriteOpTimeInTransaction, const boost::optional<OplogSlot> slot) final; void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/op_observer_noop.h b/src/mongo/db/op_observer_noop.h index 2d4cb62da31..0a90da9d0d1 100644 --- a/src/mongo/db/op_observer_noop.h +++ b/src/mongo/db/op_observer_noop.h @@ -92,7 +92,7 @@ public: const boost::optional<repl::OpTime> prevWriteOpTimeInTransaction, const boost::optional<OplogSlot> slot) override {} void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/op_observer_registry.h b/src/mongo/db/op_observer_registry.h index 6988b0560bb..029393ef199 100644 --- a/src/mongo/db/op_observer_registry.h +++ b/src/mongo/db/op_observer_registry.h @@ -172,7 +172,7 @@ public: } void onCreateCollection(OperationContext* const opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/ops/delete.cpp b/src/mongo/db/ops/delete.cpp index ea988e53c6c..14b81cc207b 100644 --- a/src/mongo/db/ops/delete.cpp +++ b/src/mongo/db/ops/delete.cpp @@ -41,7 +41,7 @@ namespace mongo { long long deleteObjects(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const NamespaceString& ns, BSONObj pattern, bool justOne, diff --git a/src/mongo/db/ops/delete.h b/src/mongo/db/ops/delete.h index b26f583d460..58eebd434d7 100644 --- a/src/mongo/db/ops/delete.h +++ b/src/mongo/db/ops/delete.h @@ -44,7 +44,7 @@ class OperationContext; * not yield. If 'god' is true, deletes are allowed on system namespaces. */ long long deleteObjects(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const NamespaceString& ns, BSONObj pattern, bool justOne, diff --git a/src/mongo/db/ops/update.cpp b/src/mongo/db/ops/update.cpp index 56c69a9c662..da11e24b03d 100644 --- a/src/mongo/db/ops/update.cpp +++ b/src/mongo/db/ops/update.cpp @@ -62,7 +62,7 @@ UpdateResult update(OperationContext* opCtx, Database* db, const UpdateRequest& const NamespaceString& nsString = request.getNamespaceString(); invariant(opCtx->lockState()->isCollectionLockedForMode(nsString, MODE_IX)); - Collection* collection; + const Collection* collection; // The update stage does not create its own collection. As such, if the update is // an upsert, create the collection that the update stage inserts into beforehand. diff --git a/src/mongo/db/ops/write_ops_exec.cpp b/src/mongo/db/ops/write_ops_exec.cpp index 62401613f07..e6b5209488a 100644 --- a/src/mongo/db/ops/write_ops_exec.cpp +++ b/src/mongo/db/ops/write_ops_exec.cpp @@ -281,7 +281,7 @@ bool handleError(OperationContext* opCtx, } void insertDocuments(OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::vector<InsertStatement>::iterator begin, std::vector<InsertStatement>::iterator end, bool fromMigrate) { @@ -336,7 +336,7 @@ void insertDocuments(OperationContext* opCtx, * they only allow one operation at a time because they enforce insertion order with a MODE_X * collection lock, which we cannot hold in transactions. */ -Status checkIfTransactionOnCappedColl(OperationContext* opCtx, Collection* collection) { +Status checkIfTransactionOnCappedColl(OperationContext* opCtx, const Collection* collection) { if (opCtx->inMultiDocumentTransaction() && collection->isCapped()) { return {ErrorCodes::OperationNotSupportedInTransaction, str::stream() << "Collection '" << collection->ns() diff --git a/src/mongo/db/pipeline/document_source_check_resume_token_test.cpp b/src/mongo/db/pipeline/document_source_check_resume_token_test.cpp index e6d3cda6a24..71f01ec190c 100644 --- a/src/mongo/db/pipeline/document_source_check_resume_token_test.cpp +++ b/src/mongo/db/pipeline/document_source_check_resume_token_test.cpp @@ -124,10 +124,7 @@ public: return std::make_unique<ChangeStreamOplogCursorMock>(&_records); } - const RecordStore* getRecordStore() const override { - return _recordStore.get(); - } - RecordStore* getRecordStore() override { + RecordStore* getRecordStore() const override { return _recordStore.get(); } diff --git a/src/mongo/db/query/collection_query_info.cpp b/src/mongo/db/query/collection_query_info.cpp index aaef235f02b..1992422d141 100644 --- a/src/mongo/db/query/collection_query_info.cpp +++ b/src/mongo/db/query/collection_query_info.cpp @@ -87,7 +87,7 @@ const UpdateIndexData& CollectionQueryInfo::getIndexKeys(OperationContext* opCtx return _indexedPaths; } -void CollectionQueryInfo::computeIndexKeys(OperationContext* opCtx, Collection* coll) { +void CollectionQueryInfo::computeIndexKeys(OperationContext* opCtx, const Collection* coll) { _indexedPaths.clear(); std::unique_ptr<IndexCatalog::IndexIterator> it = @@ -195,7 +195,8 @@ PlanCache* CollectionQueryInfo::getPlanCache() const { return _planCache.get(); } -void CollectionQueryInfo::updatePlanCacheIndexEntries(OperationContext* opCtx, Collection* coll) { +void CollectionQueryInfo::updatePlanCacheIndexEntries(OperationContext* opCtx, + const Collection* coll) { std::vector<CoreIndexInfo> indexCores; // TODO We shouldn't need to include unfinished indexes, but we must here because the index @@ -211,7 +212,7 @@ void CollectionQueryInfo::updatePlanCacheIndexEntries(OperationContext* opCtx, C _planCache->notifyOfIndexUpdates(indexCores); } -void CollectionQueryInfo::init(OperationContext* opCtx, Collection* coll) { +void CollectionQueryInfo::init(OperationContext* opCtx, const Collection* coll) { const bool includeUnfinishedIndexes = false; std::unique_ptr<IndexCatalog::IndexIterator> ii = coll->getIndexCatalog()->getIndexIterator(opCtx, includeUnfinishedIndexes); @@ -225,7 +226,7 @@ void CollectionQueryInfo::init(OperationContext* opCtx, Collection* coll) { } void CollectionQueryInfo::addedIndex(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const IndexDescriptor* desc) { invariant(desc); @@ -235,14 +236,14 @@ void CollectionQueryInfo::addedIndex(OperationContext* opCtx, } void CollectionQueryInfo::droppedIndex(OperationContext* opCtx, - Collection* coll, + const Collection* coll, StringData indexName) { rebuildIndexData(opCtx, coll); CollectionIndexUsageTrackerDecoration::get(coll->getSharedDecorations()) .unregisterIndex(indexName); } -void CollectionQueryInfo::rebuildIndexData(OperationContext* opCtx, Collection* coll) { +void CollectionQueryInfo::rebuildIndexData(OperationContext* opCtx, const Collection* coll) { clearQueryCache(coll); _keysComputed = false; diff --git a/src/mongo/db/query/collection_query_info.h b/src/mongo/db/query/collection_query_info.h index ac3a0aa2bee..d2e954610cf 100644 --- a/src/mongo/db/query/collection_query_info.h +++ b/src/mongo/db/query/collection_query_info.h @@ -63,7 +63,7 @@ public: /** * Builds internal cache state based on the current state of the Collection's IndexCatalog. */ - void init(OperationContext* opCtx, Collection* coll); + void init(OperationContext* opCtx, const Collection* coll); /** * Register a newly-created index with the cache. Must be called whenever an index is @@ -71,7 +71,7 @@ public: * * Must be called under exclusive collection lock. */ - void addedIndex(OperationContext* opCtx, Collection* coll, const IndexDescriptor* desc); + void addedIndex(OperationContext* opCtx, const Collection* coll, const IndexDescriptor* desc); /** * Deregister a newly-dropped index with the cache. Must be called whenever an index is @@ -79,7 +79,7 @@ public: * * Must be called under exclusive collection lock. */ - void droppedIndex(OperationContext* opCtx, Collection* coll, StringData indexName); + void droppedIndex(OperationContext* opCtx, const Collection* coll, StringData indexName); /** * Removes all cached query plans. @@ -91,14 +91,14 @@ public: const PlanSummaryStats& summaryStats) const; private: - void computeIndexKeys(OperationContext* opCtx, Collection* coll); - void updatePlanCacheIndexEntries(OperationContext* opCtx, Collection* coll); + void computeIndexKeys(OperationContext* opCtx, const Collection* coll); + void updatePlanCacheIndexEntries(OperationContext* opCtx, const Collection* coll); /** * Rebuilds cached information that is dependent on index composition. Must be called * when index composition changes. */ - void rebuildIndexData(OperationContext* opCtx, Collection* coll); + void rebuildIndexData(OperationContext* opCtx, const Collection* coll); // --- index keys cache bool _keysComputed; diff --git a/src/mongo/db/query/get_executor.cpp b/src/mongo/db/query/get_executor.cpp index c2f78691c43..f5706c7ffd3 100644 --- a/src/mongo/db/query/get_executor.cpp +++ b/src/mongo/db/query/get_executor.cpp @@ -1188,7 +1188,7 @@ StatusWith<std::unique_ptr<projection_ast::Projection>> makeProjection(const BSO StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> getExecutorDelete( OpDebug* opDebug, - Collection* collection, + const Collection* collection, ParsedDelete* parsedDelete, boost::optional<ExplainOptions::Verbosity> verbosity) { auto expCtx = parsedDelete->expCtx(); @@ -1346,7 +1346,7 @@ StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> getExecutorDele StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> getExecutorUpdate( OpDebug* opDebug, - Collection* collection, + const Collection* collection, ParsedUpdate* parsedUpdate, boost::optional<ExplainOptions::Verbosity> verbosity) { auto expCtx = parsedUpdate->expCtx(); diff --git a/src/mongo/db/query/get_executor.h b/src/mongo/db/query/get_executor.h index c4f584a3c82..d14e07f9da3 100644 --- a/src/mongo/db/query/get_executor.h +++ b/src/mongo/db/query/get_executor.h @@ -240,7 +240,7 @@ StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> getExecutorCoun */ StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> getExecutorDelete( OpDebug* opDebug, - Collection* collection, + const Collection* collection, ParsedDelete* parsedDelete, boost::optional<ExplainOptions::Verbosity> verbosity); @@ -266,7 +266,7 @@ StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> getExecutorDele */ StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> getExecutorUpdate( OpDebug* opDebug, - Collection* collection, + const Collection* collection, ParsedUpdate* parsedUpdate, boost::optional<ExplainOptions::Verbosity> verbosity); } // namespace mongo diff --git a/src/mongo/db/query/internal_plans.cpp b/src/mongo/db/query/internal_plans.cpp index 264a467492f..8d4f5d8ca47 100644 --- a/src/mongo/db/query/internal_plans.cpp +++ b/src/mongo/db/query/internal_plans.cpp @@ -82,7 +82,7 @@ std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> InternalPlanner::collection std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> InternalPlanner::deleteWithCollectionScan( OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::unique_ptr<DeleteStageParams> params, PlanYieldPolicy::YieldPolicy yieldPolicy, Direction direction) { @@ -137,7 +137,7 @@ std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> InternalPlanner::indexScan( std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> InternalPlanner::deleteWithIndexScan( OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::unique_ptr<DeleteStageParams> params, const IndexDescriptor* descriptor, const BSONObj& startKey, @@ -172,7 +172,7 @@ std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> InternalPlanner::deleteWith std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> InternalPlanner::updateWithIdHack( OperationContext* opCtx, - Collection* collection, + const Collection* collection, const UpdateStageParams& params, const IndexDescriptor* descriptor, const BSONObj& key, diff --git a/src/mongo/db/query/internal_plans.h b/src/mongo/db/query/internal_plans.h index 0dc87bc96cd..3846dca76bc 100644 --- a/src/mongo/db/query/internal_plans.h +++ b/src/mongo/db/query/internal_plans.h @@ -82,7 +82,7 @@ public: */ static std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> deleteWithCollectionScan( OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::unique_ptr<DeleteStageParams> params, PlanYieldPolicy::YieldPolicy yieldPolicy, Direction direction = FORWARD); @@ -106,7 +106,7 @@ public: */ static std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> deleteWithIndexScan( OperationContext* opCtx, - Collection* collection, + const Collection* collection, std::unique_ptr<DeleteStageParams> params, const IndexDescriptor* descriptor, const BSONObj& startKey, @@ -120,7 +120,7 @@ public: */ static std::unique_ptr<PlanExecutor, PlanExecutor::Deleter> updateWithIdHack( OperationContext* opCtx, - Collection* collection, + const Collection* collection, const UpdateStageParams& params, const IndexDescriptor* descriptor, const BSONObj& key, diff --git a/src/mongo/db/rebuild_indexes.cpp b/src/mongo/db/rebuild_indexes.cpp index 1108a4e0142..ea35ad418b8 100644 --- a/src/mongo/db/rebuild_indexes.cpp +++ b/src/mongo/db/rebuild_indexes.cpp @@ -92,7 +92,7 @@ StatusWith<IndexNameObjs> getIndexNameObjs(OperationContext* opCtx, } Status rebuildIndexesOnCollection(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const std::vector<BSONObj>& indexSpecs, RepairData repair) { // Skip the rest if there are no indexes to rebuild. diff --git a/src/mongo/db/rebuild_indexes.h b/src/mongo/db/rebuild_indexes.h index 1654e359882..20ef0e7aff6 100644 --- a/src/mongo/db/rebuild_indexes.h +++ b/src/mongo/db/rebuild_indexes.h @@ -61,7 +61,7 @@ StatusWith<IndexNameObjs> getIndexNameObjs(OperationContext* opCtx, */ enum class RepairData { kYes, kNo }; Status rebuildIndexesOnCollection(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const std::vector<BSONObj>& indexSpecs, RepairData repair); @@ -70,7 +70,7 @@ Status rebuildIndexesOnCollection(OperationContext* opCtx, * One example usage is when a 'dropIndex' command is rolled back. The dropped index must be remade. */ Status rebuildIndexesOnCollection(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const std::vector<BSONObj>& indexSpecs); } // namespace mongo diff --git a/src/mongo/db/repair.cpp b/src/mongo/db/repair.cpp index b892165cd44..0c06a70d3f9 100644 --- a/src/mongo/db/repair.cpp +++ b/src/mongo/db/repair.cpp @@ -201,12 +201,14 @@ Status repairCollection(OperationContext* opCtx, LOGV2(21027, "Repairing collection", "namespace"_attr = nss); - auto collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); + auto collection = + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, nss); Status status = engine->repairRecordStore(opCtx, collection->getCatalogId(), nss); // Need to lookup from catalog again because the old collection object was invalidated by // repairRecordStore. - collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); + collection = + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, nss); // If data was modified during repairRecordStore, we know to rebuild indexes without needing // to run an expensive collection validation. diff --git a/src/mongo/db/repl/apply_ops.cpp b/src/mongo/db/repl/apply_ops.cpp index 076146c191f..0caf8565939 100644 --- a/src/mongo/db/repl/apply_ops.cpp +++ b/src/mongo/db/repl/apply_ops.cpp @@ -315,7 +315,7 @@ Status _checkPrecondition(OperationContext* opCtx, if (!database) { return {ErrorCodes::NamespaceNotFound, "database in ns does not exist: " + nss.ns()}; } - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); if (!collection) { return {ErrorCodes::NamespaceNotFound, "collection in ns does not exist: " + nss.ns()}; diff --git a/src/mongo/db/repl/collection_bulk_loader_impl.cpp b/src/mongo/db/repl/collection_bulk_loader_impl.cpp index 2dc390c8e54..eab00297cdd 100644 --- a/src/mongo/db/repl/collection_bulk_loader_impl.cpp +++ b/src/mongo/db/repl/collection_bulk_loader_impl.cpp @@ -60,12 +60,11 @@ CollectionBulkLoaderImpl::CollectionBulkLoaderImpl(ServiceContext::UniqueClient& : _client{std::move(client)}, _opCtx{std::move(opCtx)}, _autoColl{std::move(autoColl)}, - _collection{_autoColl->getCollection()}, + _collection{_autoColl->getWritableCollection()}, _nss{_autoColl->getCollection()->ns()}, _idIndexBlock(std::make_unique<MultiIndexBlock>()), _secondaryIndexesBlock(std::make_unique<MultiIndexBlock>()), _idIndexSpec(idIndexSpec.getOwned()) { - invariant(_opCtx); invariant(_collection); } diff --git a/src/mongo/db/repl/dbcheck.cpp b/src/mongo/db/repl/dbcheck.cpp index c25d7bd939a..7da0b9c64a9 100644 --- a/src/mongo/db/repl/dbcheck.cpp +++ b/src/mongo/db/repl/dbcheck.cpp @@ -172,7 +172,7 @@ std::unique_ptr<HealthLogEntry> dbCheckBatchEntry(const NamespaceString& nss, } DbCheckHasher::DbCheckHasher(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const BSONKey& start, const BSONKey& end, int64_t maxCount, @@ -233,7 +233,7 @@ std::string hashCollectionInfo(const DbCheckCollectionInformation& info) { } std::pair<boost::optional<UUID>, boost::optional<UUID>> getPrevAndNextUUIDs( - OperationContext* opCtx, Collection* collection) { + OperationContext* opCtx, const Collection* collection) { const CollectionCatalog& catalog = CollectionCatalog::get(opCtx); const UUID uuid = collection->uuid(); @@ -350,7 +350,7 @@ bool DbCheckHasher::_canHash(const BSONObj& obj) { return true; } -std::vector<BSONObj> collectionIndexInfo(OperationContext* opCtx, Collection* collection) { +std::vector<BSONObj> collectionIndexInfo(OperationContext* opCtx, const Collection* collection) { std::vector<BSONObj> result; std::vector<std::string> names; @@ -370,7 +370,7 @@ std::vector<BSONObj> collectionIndexInfo(OperationContext* opCtx, Collection* co return result; } -BSONObj collectionOptions(OperationContext* opCtx, Collection* collection) { +BSONObj collectionOptions(OperationContext* opCtx, const Collection* collection) { return DurableCatalog::get(opCtx) ->getCollectionOptions(opCtx, collection->getCatalogId()) .toBSON(); @@ -408,7 +408,7 @@ Status dbCheckBatchOnSecondary(OperationContext* opCtx, const repl::OpTime& optime, const DbCheckOplogBatch& entry) { AutoGetCollectionForDbCheck agc(opCtx, entry.getNss(), entry.getType()); - Collection* collection = agc.getCollection(); + const Collection* collection = agc.getCollection(); std::string msg = "replication consistency check"; if (!collection) { diff --git a/src/mongo/db/repl/dbcheck.h b/src/mongo/db/repl/dbcheck.h index 240c20bb293..99c28b4be59 100644 --- a/src/mongo/db/repl/dbcheck.h +++ b/src/mongo/db/repl/dbcheck.h @@ -82,8 +82,8 @@ struct DbCheckCollectionInformation { * Returns a pair of previous and next UUIDs around the given collections uuid. If there is no * previous or next UUID, return boost::none respectively. */ -std::pair<boost::optional<UUID>, boost::optional<UUID>> getPrevAndNextUUIDs(OperationContext* opCtx, - Collection* collection); +std::pair<boost::optional<UUID>, boost::optional<UUID>> getPrevAndNextUUIDs( + OperationContext* opCtx, const Collection* collection); /** * Get a HealthLogEntry for a dbCheck collection. @@ -118,7 +118,7 @@ public: * @param maxBytes The maximum number of bytes to hash. */ DbCheckHasher(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const BSONKey& start, const BSONKey& end, int64_t maxCount = std::numeric_limits<int64_t>::max(), @@ -191,26 +191,26 @@ public: AutoGetCollectionForDbCheck(OperationContext* opCtx, const NamespaceString& nss, const OplogEntriesEnum& type); - Collection* getCollection(void) { + const Collection* getCollection(void) { return _collection; } private: AutoGetDbForDbCheck _agd; Lock::CollectionLock _collLock; - Collection* _collection; + const Collection* _collection; }; /** * Gather the index information for a collection. */ -std::vector<BSONObj> collectionIndexInfo(OperationContext* opCtx, Collection* collection); +std::vector<BSONObj> collectionIndexInfo(OperationContext* opCtx, const Collection* collection); /** * Gather other information for a collection. */ -BSONObj collectionOptions(OperationContext* opCtx, Collection* collection); +BSONObj collectionOptions(OperationContext* opCtx, const Collection* collection); namespace repl { diff --git a/src/mongo/db/repl/local_oplog_info.cpp b/src/mongo/db/repl/local_oplog_info.cpp index b36ff67d59e..01f48ac47b5 100644 --- a/src/mongo/db/repl/local_oplog_info.cpp +++ b/src/mongo/db/repl/local_oplog_info.cpp @@ -81,11 +81,11 @@ void LocalOplogInfo::setOplogCollectionName(ServiceContext* service) { } } -Collection* LocalOplogInfo::getCollection() const { +const Collection* LocalOplogInfo::getCollection() const { return _oplog; } -void LocalOplogInfo::setCollection(Collection* oplog) { +void LocalOplogInfo::setCollection(const Collection* oplog) { _oplog = oplog; } diff --git a/src/mongo/db/repl/local_oplog_info.h b/src/mongo/db/repl/local_oplog_info.h index 96cdb259f36..417901e4f4f 100644 --- a/src/mongo/db/repl/local_oplog_info.h +++ b/src/mongo/db/repl/local_oplog_info.h @@ -66,8 +66,8 @@ public: */ void setOplogCollectionName(ServiceContext* service); - Collection* getCollection() const; - void setCollection(Collection* oplog); + const Collection* getCollection() const; + void setCollection(const Collection* oplog); void resetCollection(); /** @@ -88,7 +88,7 @@ private: // The "oplog" pointer is always valid (or null) because an operation must take the global // exclusive lock to set the pointer to null when the Collection instance is destroyed. See // "oplogCheckCloseDatabase". - Collection* _oplog = nullptr; + const Collection* _oplog = nullptr; // Synchronizes the section where a new Timestamp is generated and when it is registered in the // storage engine. diff --git a/src/mongo/db/repl/oplog.cpp b/src/mongo/db/repl/oplog.cpp index 05fa6ecb4b8..c0a153252eb 100644 --- a/src/mongo/db/repl/oplog.cpp +++ b/src/mongo/db/repl/oplog.cpp @@ -213,7 +213,7 @@ void _logOpsInner(OperationContext* opCtx, const NamespaceString& nss, std::vector<Record>* records, const std::vector<Timestamp>& timestamps, - Collection* oplogCollection, + const Collection* oplogCollection, OpTime finalOpTime, Date_t wallTime) { auto replCoord = ReplicationCoordinator::get(opCtx); @@ -536,7 +536,7 @@ void createOplog(OperationContext* opCtx, const ReplSettings& replSettings = ReplicationCoordinator::get(opCtx)->getSettings(); OldClientContext ctx(opCtx, oplogCollectionName.ns()); - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, oplogCollectionName); if (collection) { @@ -981,7 +981,7 @@ Status applyOperation_inlock(OperationContext* opCtx, } NamespaceString requestNss; - Collection* collection = nullptr; + const Collection* collection = nullptr; if (auto uuid = op.getUuid()) { CollectionCatalog& catalog = CollectionCatalog::get(opCtx); collection = catalog.lookupCollectionByUUID(opCtx, uuid.get()); @@ -1019,7 +1019,8 @@ Status applyOperation_inlock(OperationContext* opCtx, if (op.getObject2()) o2 = op.getObject2().get(); - IndexCatalog* indexCatalog = collection == nullptr ? nullptr : collection->getIndexCatalog(); + const IndexCatalog* indexCatalog = + collection == nullptr ? nullptr : collection->getIndexCatalog(); const bool haveWrappingWriteUnitOfWork = opCtx->lockState()->inAWriteUnitOfWork(); uassert(ErrorCodes::CommandNotSupportedOnView, str::stream() << "applyOps not supported on view: " << requestNss.ns(), @@ -1753,7 +1754,7 @@ void acquireOplogCollectionForLogging(OperationContext* opCtx) { } } -void establishOplogCollectionForLogging(OperationContext* opCtx, Collection* oplog) { +void establishOplogCollectionForLogging(OperationContext* opCtx, const Collection* oplog) { invariant(opCtx->lockState()->isW()); invariant(oplog); LocalOplogInfo::get(opCtx)->setCollection(oplog); diff --git a/src/mongo/db/repl/oplog.h b/src/mongo/db/repl/oplog.h index eaac4f4eadc..17781db4df3 100644 --- a/src/mongo/db/repl/oplog.h +++ b/src/mongo/db/repl/oplog.h @@ -148,7 +148,7 @@ void acquireOplogCollectionForLogging(OperationContext* opCtx); * Called by catalog::openCatalog() to re-establish the oplog collection pointer while holding onto * the global lock in exclusive mode. */ -void establishOplogCollectionForLogging(OperationContext* opCtx, Collection* oplog); +void establishOplogCollectionForLogging(OperationContext* opCtx, const Collection* oplog); using IncrementOpsAppliedStatsFn = std::function<void()>; diff --git a/src/mongo/db/repl/oplog_applier_impl_test.cpp b/src/mongo/db/repl/oplog_applier_impl_test.cpp index edf9a5973a7..9862126d7e2 100644 --- a/src/mongo/db/repl/oplog_applier_impl_test.cpp +++ b/src/mongo/db/repl/oplog_applier_impl_test.cpp @@ -349,7 +349,7 @@ TEST_F(OplogApplierImplTest, applyOplogEntryOrGroupedInsertsCommand) { << BSON("create" << nss.coll()) << "ts" << Timestamp(1, 1) << "ui" << UUID::gen()); bool applyCmdCalled = false; _opObserver->onCreateCollectionFn = [&](OperationContext* opCtx, - Collection*, + const Collection*, const NamespaceString& collNss, const CollectionOptions&, const BSONObj&) { diff --git a/src/mongo/db/repl/oplog_applier_impl_test_fixture.cpp b/src/mongo/db/repl/oplog_applier_impl_test_fixture.cpp index cb390508c6c..d75b6469b4a 100644 --- a/src/mongo/db/repl/oplog_applier_impl_test_fixture.cpp +++ b/src/mongo/db/repl/oplog_applier_impl_test_fixture.cpp @@ -89,7 +89,7 @@ void OplogApplierImplOpObserver::onUpdate(OperationContext* opCtx, } void OplogApplierImplOpObserver::onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/repl/oplog_applier_impl_test_fixture.h b/src/mongo/db/repl/oplog_applier_impl_test_fixture.h index 4a164b04e71..1a6c414d182 100644 --- a/src/mongo/db/repl/oplog_applier_impl_test_fixture.h +++ b/src/mongo/db/repl/oplog_applier_impl_test_fixture.h @@ -99,7 +99,7 @@ public: * Called when OplogApplierImpl creates a collection. */ void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, @@ -121,7 +121,7 @@ public: std::function<void(OperationContext*, const OplogUpdateEntryArgs&)> onUpdateFn; std::function<void(OperationContext*, - Collection*, + const Collection*, const NamespaceString&, const CollectionOptions&, const BSONObj&)> diff --git a/src/mongo/db/repl/primary_only_service_op_observer.h b/src/mongo/db/repl/primary_only_service_op_observer.h index 9da7153560c..7b176eb663e 100644 --- a/src/mongo/db/repl/primary_only_service_op_observer.h +++ b/src/mongo/db/repl/primary_only_service_op_observer.h @@ -108,7 +108,7 @@ public: const boost::optional<OplogSlot> slot) final {} void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/repl/replication_recovery.cpp b/src/mongo/db/repl/replication_recovery.cpp index dd350f73552..bba59beb626 100644 --- a/src/mongo/db/repl/replication_recovery.cpp +++ b/src/mongo/db/repl/replication_recovery.cpp @@ -649,7 +649,7 @@ void ReplicationRecoveryImpl::_truncateOplogTo(OperationContext* opCtx, AutoGetDb autoDb(opCtx, oplogNss.db(), MODE_IX); Lock::CollectionLock oplogCollectionLoc(opCtx, oplogNss, MODE_X); Collection* oplogCollection = - CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, oplogNss); + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, oplogNss); if (!oplogCollection) { fassertFailedWithStatusNoTrace( 34418, diff --git a/src/mongo/db/repl/rs_rollback.cpp b/src/mongo/db/repl/rs_rollback.cpp index d2116a74b17..6c3480157e9 100644 --- a/src/mongo/db/repl/rs_rollback.cpp +++ b/src/mongo/db/repl/rs_rollback.cpp @@ -907,7 +907,8 @@ void rollbackCreateIndexes(OperationContext* opCtx, UUID uuid, std::set<std::str CollectionCatalog::get(opCtx).lookupNSSByUUID(opCtx, uuid); invariant(nss); Lock::DBLock dbLock(opCtx, nss->db(), MODE_X); - Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, uuid); + Collection* collection = + CollectionCatalog::get(opCtx).lookupCollectionByUUIDForMetadataWrite(opCtx, uuid); // If we cannot find the collection, we skip over dropping the index. if (!collection) { @@ -970,7 +971,8 @@ void rollbackDropIndexes(OperationContext* opCtx, invariant(nss); Lock::DBLock dbLock(opCtx, nss->db(), MODE_IX); Lock::CollectionLock collLock(opCtx, *nss, MODE_X); - Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, *nss); + const Collection* collection = + CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, *nss); // If we cannot find the collection, we skip over dropping the index. if (!collection) { @@ -1014,7 +1016,7 @@ void rollbackDropIndexes(OperationContext* opCtx, */ void dropCollection(OperationContext* opCtx, NamespaceString nss, - Collection* collection, + const Collection* collection, Database* db) { if (RollbackImpl::shouldCreateDataFiles()) { RemoveSaver removeSaver("rollback", "", collection->uuid().toString()); @@ -1497,7 +1499,7 @@ void rollback_internal::syncFixUp(OperationContext* opCtx, Database* db = dbLock.getDb(); if (db) { - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, uuid); dropCollection(opCtx, *nss, collection, db); LOGV2_DEBUG(21698, @@ -1573,7 +1575,7 @@ void rollback_internal::syncFixUp(OperationContext* opCtx, invariant(db); Collection* collection = - CollectionCatalog::get(opCtx).lookupCollectionByUUID(opCtx, uuid); + CollectionCatalog::get(opCtx).lookupCollectionByUUIDForMetadataWrite(opCtx, uuid); invariant(collection); auto infoResult = rollbackSource.getCollectionInfoByUUID(nss->db().toString(), uuid); @@ -1727,7 +1729,8 @@ void rollback_internal::syncFixUp(OperationContext* opCtx, const NamespaceString docNss(doc.ns); Lock::DBLock docDbLock(opCtx, docNss.db(), MODE_X); OldClientContext ctx(opCtx, doc.ns.toString()); - Collection* collection = catalog.lookupCollectionByUUID(opCtx, uuid); + Collection* collection = + catalog.lookupCollectionByUUIDForMetadataWrite(opCtx, uuid); // Adds the doc to our rollback file if the collection was not dropped while // rolling back createCollection operations. Does not log an error when @@ -1945,7 +1948,8 @@ void rollback_internal::syncFixUp(OperationContext* opCtx, Lock::CollectionLock oplogCollectionLoc(opCtx, oplogNss, MODE_X); OldClientContext ctx(opCtx, oplogNss.ns()); Collection* oplogCollection = - CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, oplogNss); + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, + oplogNss); if (!oplogCollection) { fassertFailedWithStatusNoTrace( 40495, diff --git a/src/mongo/db/repl/rs_rollback_test.cpp b/src/mongo/db/repl/rs_rollback_test.cpp index 7ba48ce594d..0105bd8b6eb 100644 --- a/src/mongo/db/repl/rs_rollback_test.cpp +++ b/src/mongo/db/repl/rs_rollback_test.cpp @@ -79,7 +79,7 @@ OplogInterfaceMock::Operation makeNoopOplogEntryAndRecordId(Seconds seconds) { return std::make_pair(BSON("ts" << ts.getTimestamp()), RecordId(1)); } -OplogInterfaceMock::Operation makeDropIndexOplogEntry(Collection* collection, +OplogInterfaceMock::Operation makeDropIndexOplogEntry(const Collection* collection, BSONObj key, std::string indexName, int time) { @@ -96,7 +96,7 @@ OplogInterfaceMock::Operation makeDropIndexOplogEntry(Collection* collection, RecordId(time)); } -OplogInterfaceMock::Operation makeStartIndexBuildOplogEntry(Collection* collection, +OplogInterfaceMock::Operation makeStartIndexBuildOplogEntry(const Collection* collection, UUID buildUUID, BSONObj spec, int time) { @@ -112,7 +112,7 @@ OplogInterfaceMock::Operation makeStartIndexBuildOplogEntry(Collection* collecti RecordId(time)); } -OplogInterfaceMock::Operation makeCommitIndexBuildOplogEntry(Collection* collection, +OplogInterfaceMock::Operation makeCommitIndexBuildOplogEntry(const Collection* collection, UUID buildUUID, BSONObj spec, int time) { @@ -128,7 +128,7 @@ OplogInterfaceMock::Operation makeCommitIndexBuildOplogEntry(Collection* collect RecordId(time)); } -OplogInterfaceMock::Operation makeAbortIndexBuildOplogEntry(Collection* collection, +OplogInterfaceMock::Operation makeAbortIndexBuildOplogEntry(const Collection* collection, UUID buildUUID, BSONObj spec, int time) { @@ -150,7 +150,7 @@ OplogInterfaceMock::Operation makeAbortIndexBuildOplogEntry(Collection* collecti RecordId(time)); } -OplogInterfaceMock::Operation makeCreateIndexOplogEntry(Collection* collection, +OplogInterfaceMock::Operation makeCreateIndexOplogEntry(const Collection* collection, BSONObj key, std::string indexName, int time) { @@ -847,14 +847,14 @@ BSONObj idxSpec(NamespaceString nss, std::string id) { } // Returns the number of indexes that exist on the given collection. -int numIndexesOnColl(OperationContext* opCtx, NamespaceString nss, Collection* coll) { +int numIndexesOnColl(OperationContext* opCtx, NamespaceString nss, const Collection* coll) { Lock::DBLock dbLock(opCtx, nss.db(), MODE_X); auto indexCatalog = coll->getIndexCatalog(); ASSERT(indexCatalog); return indexCatalog->numIndexesReady(opCtx); } -int numIndexesInProgress(OperationContext* opCtx, NamespaceString nss, Collection* coll) { +int numIndexesInProgress(OperationContext* opCtx, NamespaceString nss, const Collection* coll) { Lock::DBLock dbLock(opCtx, nss.db(), MODE_X); auto indexCatalog = coll->getIndexCatalog(); ASSERT(indexCatalog); @@ -1738,7 +1738,7 @@ OpTime getOpTimeFromOplogEntry(const BSONObj& entry) { TEST_F(RSRollbackTest, RollbackApplyOpsCommand) { createOplog(_opCtx.get()); - Collection* coll = nullptr; + const Collection* coll = nullptr; CollectionOptions options; options.uuid = UUID::gen(); { diff --git a/src/mongo/db/repl/storage_interface.h b/src/mongo/db/repl/storage_interface.h index 1aea0e40b93..190ab591f37 100644 --- a/src/mongo/db/repl/storage_interface.h +++ b/src/mongo/db/repl/storage_interface.h @@ -325,7 +325,7 @@ public: * matches are found. */ virtual boost::optional<BSONObj> findOplogEntryLessThanOrEqualToTimestamp( - OperationContext* opCtx, Collection* oplog, const Timestamp& timestamp) = 0; + OperationContext* opCtx, const Collection* oplog, const Timestamp& timestamp) = 0; /** * Calls findOplogEntryLessThanOrEqualToTimestamp with endless WriteConflictException retries. @@ -336,7 +336,7 @@ public: * fail, say for correctness. */ virtual boost::optional<BSONObj> findOplogEntryLessThanOrEqualToTimestampRetryOnWCE( - OperationContext* opCtx, Collection* oplog, const Timestamp& timestamp) = 0; + OperationContext* opCtx, const Collection* oplog, const Timestamp& timestamp) = 0; /** * Fetches the latest oplog entry's timestamp. Bypasses the oplog visibility rules. diff --git a/src/mongo/db/repl/storage_interface_impl.cpp b/src/mongo/db/repl/storage_interface_impl.cpp index e52c11b2c15..159179530a9 100644 --- a/src/mongo/db/repl/storage_interface_impl.cpp +++ b/src/mongo/db/repl/storage_interface_impl.cpp @@ -230,8 +230,7 @@ StorageInterfaceImpl::createCollectionForBulkLoading( // Get locks and create the collection. AutoGetOrCreateDb db(opCtx.get(), nss.db(), MODE_IX); AutoGetCollection coll(opCtx.get(), nss, fixLockModeForSystemDotViewsChanges(nss, MODE_X)); - - if (coll.getCollection()) { + if (coll) { return Status(ErrorCodes::NamespaceExists, str::stream() << "Collection " << nss.ns() << " already exists."); } @@ -251,17 +250,17 @@ StorageInterfaceImpl::createCollectionForBulkLoading( if (options.capped) { WriteUnitOfWork wunit(opCtx.get()); if (!idIndexSpec.isEmpty()) { - auto status = - autoColl->getCollection()->getIndexCatalog()->createIndexOnEmptyCollection( - opCtx.get(), idIndexSpec); + auto status = autoColl->getWritableCollection() + ->getIndexCatalog() + ->createIndexOnEmptyCollection(opCtx.get(), idIndexSpec); if (!status.getStatus().isOK()) { return status.getStatus(); } } for (auto&& spec : secondaryIndexSpecs) { - auto status = - autoColl->getCollection()->getIndexCatalog()->createIndexOnEmptyCollection( - opCtx.get(), spec); + auto status = autoColl->getWritableCollection() + ->getIndexCatalog() + ->createIndexOnEmptyCollection(opCtx.get(), spec); if (!status.getStatus().isOK()) { return status.getStatus(); } @@ -300,7 +299,7 @@ Status StorageInterfaceImpl::insertDocument(OperationContext* opCtx, namespace { /** - * Returns Collection* from database RAII object. + * Returns const Collection* from database RAII object. * Returns NamespaceNotFound if the database or collection does not exist. */ template <typename AutoGetCollectionType> @@ -330,7 +329,7 @@ Status insertDocumentsSingleBatch(OperationContext* opCtx, std::vector<InsertStatement>::const_iterator end) { boost::optional<AutoGetCollection> autoColl; boost::optional<AutoGetOplog> autoOplog; - Collection* collection; + const Collection* collection; auto nss = nsOrUUID.nss(); if (nss && nss->isOplog()) { @@ -505,8 +504,8 @@ Status StorageInterfaceImpl::createIndexesOnEmptyCollection( for (auto&& spec : secondaryIndexSpecs) { // Will error if collection is not empty. auto secIndexSW = - autoColl.getCollection()->getIndexCatalog()->createIndexOnEmptyCollection(opCtx, - spec); + autoColl.getWritableCollection()->getIndexCatalog()->createIndexOnEmptyCollection( + opCtx, spec); auto status = secIndexSW.getStatus(); if (!status.isOK()) { return status; @@ -545,10 +544,9 @@ Status StorageInterfaceImpl::truncateCollection(OperationContext* opCtx, if (!collectionResult.isOK()) { return collectionResult.getStatus(); } - auto collection = collectionResult.getValue(); WriteUnitOfWork wunit(opCtx); - const auto status = collection->truncate(opCtx); + const auto status = autoColl.getWritableCollection()->truncate(opCtx); if (!status.isOK()) { return status; } @@ -1103,7 +1101,7 @@ Status StorageInterfaceImpl::deleteByFilter(OperationContext* opCtx, } boost::optional<BSONObj> StorageInterfaceImpl::findOplogEntryLessThanOrEqualToTimestamp( - OperationContext* opCtx, Collection* oplog, const Timestamp& timestamp) { + OperationContext* opCtx, const Collection* oplog, const Timestamp& timestamp) { invariant(oplog); invariant(opCtx->lockState()->isLocked()); @@ -1134,7 +1132,7 @@ boost::optional<BSONObj> StorageInterfaceImpl::findOplogEntryLessThanOrEqualToTi } boost::optional<BSONObj> StorageInterfaceImpl::findOplogEntryLessThanOrEqualToTimestampRetryOnWCE( - OperationContext* opCtx, Collection* oplogCollection, const Timestamp& timestamp) { + OperationContext* opCtx, const Collection* oplogCollection, const Timestamp& timestamp) { // Oplog reads are specially done under only MODE_IS global locks, without database or // collection level intent locks. Therefore, reads can run concurrently with validate cmds that // take collection MODE_X locks. Validate with {full:true} set calls WT::verify on the @@ -1329,11 +1327,12 @@ Status StorageInterfaceImpl::isAdminDbValid(OperationContext* opCtx) { return Status::OK(); } - Collection* const usersCollection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( - opCtx, AuthorizationManager::usersCollectionNamespace); + const Collection* const usersCollection = + CollectionCatalog::get(opCtx).lookupCollectionByNamespace( + opCtx, AuthorizationManager::usersCollectionNamespace); const bool hasUsers = usersCollection && !Helpers::findOne(opCtx, usersCollection, BSONObj(), false).isNull(); - Collection* const adminVersionCollection = + const Collection* const adminVersionCollection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( opCtx, AuthorizationManager::versionCollectionNamespace); BSONObj authSchemaVersionDocument; diff --git a/src/mongo/db/repl/storage_interface_impl.h b/src/mongo/db/repl/storage_interface_impl.h index 6c38fdd5b72..f1e3b0c325d 100644 --- a/src/mongo/db/repl/storage_interface_impl.h +++ b/src/mongo/db/repl/storage_interface_impl.h @@ -147,10 +147,10 @@ public: const BSONObj& filter) override; boost::optional<BSONObj> findOplogEntryLessThanOrEqualToTimestamp( - OperationContext* opCtx, Collection* oplog, const Timestamp& timestamp) override; + OperationContext* opCtx, const Collection* oplog, const Timestamp& timestamp) override; boost::optional<BSONObj> findOplogEntryLessThanOrEqualToTimestampRetryOnWCE( - OperationContext* opCtx, Collection* oplog, const Timestamp& timestamp) override; + OperationContext* opCtx, const Collection* oplog, const Timestamp& timestamp) override; Timestamp getLatestOplogTimestamp(OperationContext* opCtx) override; diff --git a/src/mongo/db/repl/storage_interface_impl_test.cpp b/src/mongo/db/repl/storage_interface_impl_test.cpp index 3ecdc4e68ed..1b4f9b0cfed 100644 --- a/src/mongo/db/repl/storage_interface_impl_test.cpp +++ b/src/mongo/db/repl/storage_interface_impl_test.cpp @@ -130,13 +130,12 @@ void createCollection(OperationContext* opCtx, */ int _createIndexOnEmptyCollection(OperationContext* opCtx, NamespaceString nss, BSONObj indexSpec) { Lock::DBLock dbLock(opCtx, nss.db(), MODE_X); - AutoGetCollection autoColl(opCtx, nss, MODE_X); - auto coll = autoColl.getCollection(); + AutoGetCollection coll(opCtx, nss, MODE_X); - auto indexCatalog = coll->getIndexCatalog(); + WriteUnitOfWork wunit(opCtx); + auto indexCatalog = coll.getWritableCollection()->getIndexCatalog(); ASSERT(indexCatalog); - WriteUnitOfWork wunit(opCtx); ASSERT_OK(indexCatalog->createIndexOnEmptyCollection(opCtx, indexSpec).getStatus()); wunit.commit(); diff --git a/src/mongo/db/repl/storage_interface_mock.h b/src/mongo/db/repl/storage_interface_mock.h index a57c2298110..854f6d2ca71 100644 --- a/src/mongo/db/repl/storage_interface_mock.h +++ b/src/mongo/db/repl/storage_interface_mock.h @@ -272,12 +272,12 @@ public: } boost::optional<BSONObj> findOplogEntryLessThanOrEqualToTimestamp( - OperationContext* opCtx, Collection* oplog, const Timestamp& timestamp) override { + OperationContext* opCtx, const Collection* oplog, const Timestamp& timestamp) override { return boost::none; } boost::optional<BSONObj> findOplogEntryLessThanOrEqualToTimestampRetryOnWCE( - OperationContext* opCtx, Collection* oplog, const Timestamp& timestamp) override { + OperationContext* opCtx, const Collection* oplog, const Timestamp& timestamp) override { return boost::none; } diff --git a/src/mongo/db/repl/tenant_migration_donor_service.cpp b/src/mongo/db/repl/tenant_migration_donor_service.cpp index 737d151afea..8f3fb868e7a 100644 --- a/src/mongo/db/repl/tenant_migration_donor_service.cpp +++ b/src/mongo/db/repl/tenant_migration_donor_service.cpp @@ -116,8 +116,7 @@ repl::OpTime TenantMigrationDonorService::Instance::_updateStateDocument( uassertStatusOK( writeConflictRetry(opCtx, "updateStateDoc", _stateDocumentsNS.ns(), [&]() -> Status { - AutoGetCollection autoCollection(opCtx, _stateDocumentsNS, MODE_IX); - Collection* collection = autoCollection.getCollection(); + AutoGetCollection collection(opCtx, _stateDocumentsNS, MODE_IX); if (!collection) { return Status(ErrorCodes::NamespaceNotFound, @@ -127,8 +126,8 @@ repl::OpTime TenantMigrationDonorService::Instance::_updateStateDocument( WriteUnitOfWork wuow(opCtx); const auto originalStateDocBson = _stateDoc.toBSON(); - const auto originalRecordId = - Helpers::findOne(opCtx, collection, originalStateDocBson, false /* requireIndex */); + const auto originalRecordId = Helpers::findOne( + opCtx, collection.getCollection(), originalStateDocBson, false /* requireIndex */); const auto originalSnapshot = Snapshotted<BSONObj>(opCtx->recoveryUnit()->getSnapshotId(), originalStateDocBson); invariant(!originalRecordId.isNull()); diff --git a/src/mongo/db/repl/tenant_oplog_applier_test.cpp b/src/mongo/db/repl/tenant_oplog_applier_test.cpp index 707b4cb63e5..39a07d3d0b7 100644 --- a/src/mongo/db/repl/tenant_oplog_applier_test.cpp +++ b/src/mongo/db/repl/tenant_oplog_applier_test.cpp @@ -578,7 +578,7 @@ TEST_F(TenantOplogApplierTest, ApplyCommand_Success) { << BSON("create" << nss.coll()) << "ts" << Timestamp(1, 1) << "ui" << UUID::gen()); bool applyCmdCalled = false; _opObserver->onCreateCollectionFn = [&](OperationContext* opCtx, - Collection*, + const Collection*, const NamespaceString& collNss, const CollectionOptions&, const BSONObj&) { @@ -609,7 +609,7 @@ TEST_F(TenantOplogApplierTest, ApplyCommand_WrongNSS) { << BSON("create" << nss.coll()) << "ts" << Timestamp(1, 1) << "ui" << UUID::gen()); bool applyCmdCalled = false; _opObserver->onCreateCollectionFn = [&](OperationContext* opCtx, - Collection*, + const Collection*, const NamespaceString& collNss, const CollectionOptions&, const BSONObj&) { applyCmdCalled = true; }; diff --git a/src/mongo/db/s/config_server_op_observer.h b/src/mongo/db/s/config_server_op_observer.h index d40eaadac68..f3c7b61fdd1 100644 --- a/src/mongo/db/s/config_server_op_observer.h +++ b/src/mongo/db/s/config_server_op_observer.h @@ -108,7 +108,7 @@ public: const boost::optional<OplogSlot> slot) final{}; void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/s/migration_chunk_cloner_source_legacy.cpp b/src/mongo/db/s/migration_chunk_cloner_source_legacy.cpp index 776a4e6458c..0b7b5cbc1d2 100644 --- a/src/mongo/db/s/migration_chunk_cloner_source_legacy.cpp +++ b/src/mongo/db/s/migration_chunk_cloner_source_legacy.cpp @@ -586,7 +586,7 @@ void MigrationChunkClonerSourceLegacy::_decrementOutstandingOperationTrackReques } void MigrationChunkClonerSourceLegacy::_nextCloneBatchFromIndexScan(OperationContext* opCtx, - Collection* collection, + const Collection* collection, BSONArrayBuilder* arrBuilder) { ElapsedTracker tracker(opCtx->getServiceContext()->getFastClockSource(), internalQueryExecYieldIterations.load(), @@ -655,7 +655,7 @@ void MigrationChunkClonerSourceLegacy::_nextCloneBatchFromIndexScan(OperationCon } void MigrationChunkClonerSourceLegacy::_nextCloneBatchFromCloneLocs(OperationContext* opCtx, - Collection* collection, + const Collection* collection, BSONArrayBuilder* arrBuilder) { ElapsedTracker tracker(opCtx->getServiceContext()->getFastClockSource(), internalQueryExecYieldIterations.load(), @@ -705,7 +705,7 @@ uint64_t MigrationChunkClonerSourceLegacy::getCloneBatchBufferAllocationSize() { } Status MigrationChunkClonerSourceLegacy::nextCloneBatch(OperationContext* opCtx, - Collection* collection, + const Collection* collection, BSONArrayBuilder* arrBuilder) { dassert(opCtx->lockState()->isCollectionLockedForMode(_args.getNss(), MODE_IS)); @@ -802,7 +802,7 @@ StatusWith<BSONObj> MigrationChunkClonerSourceLegacy::_callRecipient(const BSONO StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> MigrationChunkClonerSourceLegacy::_getIndexScanExecutor(OperationContext* opCtx, - Collection* const collection) { + const Collection* const collection) { // Allow multiKey based on the invariant that shard keys must be single-valued. Therefore, any // multi-key index prefixed by shard key cannot be multikey over the shard key fields. const IndexDescriptor* idx = @@ -835,7 +835,7 @@ MigrationChunkClonerSourceLegacy::_getIndexScanExecutor(OperationContext* opCtx, Status MigrationChunkClonerSourceLegacy::_storeCurrentLocs(OperationContext* opCtx) { AutoGetCollection autoColl(opCtx, _args.getNss(), MODE_IS); - Collection* const collection = autoColl.getCollection(); + const Collection* const collection = autoColl.getCollection(); if (!collection) { return {ErrorCodes::NamespaceNotFound, str::stream() << "Collection " << _args.getNss().ns() << " does not exist."}; diff --git a/src/mongo/db/s/migration_chunk_cloner_source_legacy.h b/src/mongo/db/s/migration_chunk_cloner_source_legacy.h index 8e34e2033f3..a5c1bdab2c1 100644 --- a/src/mongo/db/s/migration_chunk_cloner_source_legacy.h +++ b/src/mongo/db/s/migration_chunk_cloner_source_legacy.h @@ -159,7 +159,7 @@ public: * NOTE: Must be called with the collection lock held in at least IS mode. */ Status nextCloneBatch(OperationContext* opCtx, - Collection* collection, + const Collection* collection, BSONArrayBuilder* arrBuilder); /** @@ -221,14 +221,14 @@ private: StatusWith<BSONObj> _callRecipient(const BSONObj& cmdObj); StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> _getIndexScanExecutor( - OperationContext* opCtx, Collection* const collection); + OperationContext* opCtx, const Collection* const collection); void _nextCloneBatchFromIndexScan(OperationContext* opCtx, - Collection* collection, + const Collection* collection, BSONArrayBuilder* arrBuilder); void _nextCloneBatchFromCloneLocs(OperationContext* opCtx, - Collection* collection, + const Collection* collection, BSONArrayBuilder* arrBuilder); /** diff --git a/src/mongo/db/s/migration_chunk_cloner_source_legacy_commands.cpp b/src/mongo/db/s/migration_chunk_cloner_source_legacy_commands.cpp index 01302aa09b0..017851f43e9 100644 --- a/src/mongo/db/s/migration_chunk_cloner_source_legacy_commands.cpp +++ b/src/mongo/db/s/migration_chunk_cloner_source_legacy_commands.cpp @@ -108,7 +108,7 @@ public: return _autoColl->getDb(); } - Collection* getColl() const { + const Collection* getColl() const { invariant(_autoColl); return _autoColl->getCollection(); } diff --git a/src/mongo/db/s/migration_destination_manager.cpp b/src/mongo/db/s/migration_destination_manager.cpp index bbda14ffb22..3d8ba900e92 100644 --- a/src/mongo/db/s/migration_destination_manager.cpp +++ b/src/mongo/db/s/migration_destination_manager.cpp @@ -737,7 +737,7 @@ void MigrationDestinationManager::cloneCollectionIndexesAndOptions( // Gets the missing indexes and checks if the collection is empty (auto-healing is // possible). - auto checkEmptyOrGetMissingIndexesFromDonor = [&](Collection* collection) { + auto checkEmptyOrGetMissingIndexesFromDonor = [&](const Collection* collection) { auto indexCatalog = collection->getIndexCatalog(); auto indexSpecs = indexCatalog->removeExistingIndexesNoChecks( opCtx, collectionOptionsAndIndexes.indexSpecs); diff --git a/src/mongo/db/s/range_deletion_util.cpp b/src/mongo/db/s/range_deletion_util.cpp index eb18757a900..4ff6919fcd7 100644 --- a/src/mongo/db/s/range_deletion_util.cpp +++ b/src/mongo/db/s/range_deletion_util.cpp @@ -83,7 +83,7 @@ MONGO_FAIL_POINT_DEFINE(throwInternalErrorInDeleteRange); * enqueued for deletion. */ bool collectionUuidHasChanged(const NamespaceString& nss, - Collection* currentCollection, + const Collection* currentCollection, UUID expectedCollectionUuid) { if (!currentCollection) { @@ -121,7 +121,7 @@ bool collectionUuidHasChanged(const NamespaceString& nss, * the range failed. */ StatusWith<int> deleteNextBatch(OperationContext* opCtx, - Collection* collection, + const Collection* collection, BSONObj const& keyPattern, ChunkRange const& range, int numDocsToRemovePerBatch) { diff --git a/src/mongo/db/s/resharding_util.cpp b/src/mongo/db/s/resharding_util.cpp index d3335c21988..e11b33f7b15 100644 --- a/src/mongo/db/s/resharding_util.cpp +++ b/src/mongo/db/s/resharding_util.cpp @@ -212,7 +212,7 @@ void createSlimOplogView(OperationContext* opCtx, Database* db) { { // Create 'system.views' in a separate WUOW if it does not exist. WriteUnitOfWork wuow(opCtx); - Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( + const Collection* coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( opCtx, NamespaceString(db->getSystemViewsName())); if (!coll) { coll = db->createCollection(opCtx, NamespaceString(db->getSystemViewsName())); diff --git a/src/mongo/db/s/session_catalog_migration_destination_test.cpp b/src/mongo/db/s/session_catalog_migration_destination_test.cpp index 353e06e58c9..ab9d9916a6a 100644 --- a/src/mongo/db/s/session_catalog_migration_destination_test.cpp +++ b/src/mongo/db/s/session_catalog_migration_destination_test.cpp @@ -1728,7 +1728,8 @@ TEST_F(SessionCatalogMigrationDestinationTest, MigratingKnownStmtWhileOplogTrunc { AutoGetCollection oplogColl(opCtx, NamespaceString::kRsOplogNamespace, MODE_X); WriteUnitOfWork wuow(opCtx); - ASSERT_OK(oplogColl.getCollection()->truncate(opCtx)); // Empties the oplog collection. + ASSERT_OK( + oplogColl.getWritableCollection()->truncate(opCtx)); // Empties the oplog collection. wuow.commit(); } diff --git a/src/mongo/db/s/shard_server_op_observer.cpp b/src/mongo/db/s/shard_server_op_observer.cpp index f8e80658e21..70d6da97ec1 100644 --- a/src/mongo/db/s/shard_server_op_observer.cpp +++ b/src/mongo/db/s/shard_server_op_observer.cpp @@ -459,7 +459,7 @@ void ShardServerOpObserver::onDelete(OperationContext* opCtx, } void ShardServerOpObserver::onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/s/shard_server_op_observer.h b/src/mongo/db/s/shard_server_op_observer.h index 8a3beea80a9..d608611570f 100644 --- a/src/mongo/db/s/shard_server_op_observer.h +++ b/src/mongo/db/s/shard_server_op_observer.h @@ -106,7 +106,7 @@ public: const boost::optional<OplogSlot> slot) final{}; void onCreateCollection(OperationContext* opCtx, - Collection* coll, + const Collection* coll, const NamespaceString& collectionName, const CollectionOptions& options, const BSONObj& idIndex, diff --git a/src/mongo/db/s/split_chunk.cpp b/src/mongo/db/s/split_chunk.cpp index 847f43d7111..b46885c3f1b 100644 --- a/src/mongo/db/s/split_chunk.cpp +++ b/src/mongo/db/s/split_chunk.cpp @@ -58,7 +58,7 @@ namespace { const ReadPreferenceSetting kPrimaryOnlyReadPreference{ReadPreference::PrimaryOnly}; bool checkIfSingleDoc(OperationContext* opCtx, - Collection* collection, + const Collection* collection, const IndexDescriptor* idx, const ChunkType* chunk) { KeyPattern kp(idx->keyPattern()); @@ -210,7 +210,7 @@ StatusWith<boost::optional<ChunkRange>> splitChunk(OperationContext* opCtx, AutoGetCollection autoColl(opCtx, nss, MODE_IS); - Collection* const collection = autoColl.getCollection(); + const Collection* const collection = autoColl.getCollection(); if (!collection) { LOGV2_WARNING( 23778, diff --git a/src/mongo/db/s/split_vector.cpp b/src/mongo/db/s/split_vector.cpp index 10819bbcc8d..67daf15550f 100644 --- a/src/mongo/db/s/split_vector.cpp +++ b/src/mongo/db/s/split_vector.cpp @@ -78,7 +78,7 @@ std::vector<BSONObj> splitVector(OperationContext* opCtx, { AutoGetCollection autoColl(opCtx, nss, MODE_IS); - Collection* const collection = autoColl.getCollection(); + const Collection* const collection = autoColl.getCollection(); uassert(ErrorCodes::NamespaceNotFound, "ns not found", collection); // Allow multiKey based on the invariant that shard keys must be single-valued. Therefore, diff --git a/src/mongo/db/startup_recovery.cpp b/src/mongo/db/startup_recovery.cpp index 11d38fa42c3..309ffa96180 100644 --- a/src/mongo/db/startup_recovery.cpp +++ b/src/mongo/db/startup_recovery.cpp @@ -105,7 +105,7 @@ Status restoreMissingFeatureCompatibilityVersionDocument(OperationContext* opCtx createCollection(opCtx, fcvNss.db().toString(), BSON("create" << fcvNss.coll()))); } - Collection* fcvColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( + const Collection* fcvColl = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( opCtx, NamespaceString::kServerConfigurationNamespace); invariant(fcvColl); @@ -320,7 +320,7 @@ bool hasReplSetConfigDoc(OperationContext* opCtx) { void assertCappedOplog(OperationContext* opCtx, Database* db) { const NamespaceString oplogNss(NamespaceString::kRsOplogNamespace); invariant(opCtx->lockState()->isDbLockedForMode(oplogNss.db(), MODE_IS)); - Collection* oplogCollection = + const Collection* oplogCollection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, oplogNss); if (oplogCollection && !oplogCollection->isCapped()) { LOGV2_FATAL_NOTRACE( @@ -419,7 +419,7 @@ void setReplSetMemberInStandaloneMode(OperationContext* opCtx) { } invariant(opCtx->lockState()->isW()); - Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( opCtx, NamespaceString::kSystemReplSetNamespace); if (collection && !collection->isEmpty(opCtx)) { setReplSetMemberInStandaloneMode(opCtx->getServiceContext(), true); diff --git a/src/mongo/db/storage/storage_debug_util.cpp b/src/mongo/db/storage/storage_debug_util.cpp index ca7a1eaed42..a17de8927f4 100644 --- a/src/mongo/db/storage/storage_debug_util.cpp +++ b/src/mongo/db/storage/storage_debug_util.cpp @@ -75,8 +75,7 @@ void printKeyString(const RecordId& recordId, void printCollectionAndIndexTableEntries(OperationContext* opCtx, const NamespaceString& nss) { invariant(!opCtx->lockState()->isLocked()); - AutoGetCollection autoColl(opCtx, nss, MODE_IS); - Collection* coll = autoColl.getCollection(); + AutoGetCollection coll(opCtx, nss, MODE_IS); LOGV2(51807, "Dumping collection table and index tables' entries for debugging..."); diff --git a/src/mongo/db/storage/storage_engine_test_fixture.h b/src/mongo/db/storage/storage_engine_test_fixture.h index 074904803ad..cada701556d 100644 --- a/src/mongo/db/storage/storage_engine_test_fixture.h +++ b/src/mongo/db/storage/storage_engine_test_fixture.h @@ -157,7 +157,7 @@ public: } BSONObj spec = builder.append("name", key).append("v", 2).done(); - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, collNs); auto descriptor = std::make_unique<IndexDescriptor>(collection, IndexNames::findPluginName(spec), spec); @@ -171,13 +171,13 @@ public: } void indexBuildSuccess(OperationContext* opCtx, NamespaceString collNs, std::string key) { - Collection* collection = + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, collNs); DurableCatalog::get(opCtx)->indexBuildSuccess(opCtx, collection->getCatalogId(), key); } Status removeEntry(OperationContext* opCtx, StringData collNs, DurableCatalog* catalog) { - Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( + const Collection* collection = CollectionCatalog::get(opCtx).lookupCollectionByNamespace( opCtx, NamespaceString(collNs)); return dynamic_cast<DurableCatalogImpl*>(catalog)->_removeEntry(opCtx, collection->getCatalogId()); diff --git a/src/mongo/db/storage/wiredtiger/wiredtiger_index.h b/src/mongo/db/storage/wiredtiger/wiredtiger_index.h index 2919183896f..f5dc594d30b 100644 --- a/src/mongo/db/storage/wiredtiger/wiredtiger_index.h +++ b/src/mongo/db/storage/wiredtiger/wiredtiger_index.h @@ -120,7 +120,7 @@ public: virtual Status initAsEmpty(OperationContext* opCtx); - virtual Status compact(OperationContext* opCtx); + Status compact(OperationContext* opCtx) override; const std::string& uri() const { return _uri; diff --git a/src/mongo/db/system_index.cpp b/src/mongo/db/system_index.cpp index 0b3c022dba4..9234ad7769b 100644 --- a/src/mongo/db/system_index.cpp +++ b/src/mongo/db/system_index.cpp @@ -143,10 +143,10 @@ Status verifySystemIndexes(OperationContext* opCtx) { // Create indexes for the admin.system.users collection. { - AutoGetCollection autoColl(opCtx, systemUsers, MODE_X); + AutoGetCollection collection(opCtx, systemUsers, MODE_X); - if (Collection* collection = autoColl.getCollection()) { - IndexCatalog* indexCatalog = collection->getIndexCatalog(); + if (collection) { + const IndexCatalog* indexCatalog = collection->getIndexCatalog(); invariant(indexCatalog); // Make sure the old unique index from v2.4 on system.users doesn't exist. @@ -176,11 +176,11 @@ Status verifySystemIndexes(OperationContext* opCtx) { // Create indexes for the admin.system.roles collection. { - AutoGetCollection autoColl(opCtx, systemRoles, MODE_X); + AutoGetCollection collection(opCtx, systemRoles, MODE_X); // Ensure that system indexes exist for the roles collection, if it exists. - if (Collection* collection = autoColl.getCollection()) { - IndexCatalog* indexCatalog = collection->getIndexCatalog(); + if (collection) { + const IndexCatalog* indexCatalog = collection->getIndexCatalog(); invariant(indexCatalog); std::vector<const IndexDescriptor*> indexes; @@ -199,7 +199,7 @@ Status verifySystemIndexes(OperationContext* opCtx) { return Status::OK(); } -void createSystemIndexes(OperationContext* opCtx, Collection* collection) { +void createSystemIndexes(OperationContext* opCtx, const Collection* collection) { invariant(collection); const NamespaceString& ns = collection->ns(); BSONObj indexSpec; diff --git a/src/mongo/db/system_index.h b/src/mongo/db/system_index.h index ace6d0f8aad..02eb4d26b4a 100644 --- a/src/mongo/db/system_index.h +++ b/src/mongo/db/system_index.h @@ -39,7 +39,7 @@ class Status; * Creates the appropriate indexes on _new_ system collections for authentication, * authorization, and sessions. */ -void createSystemIndexes(OperationContext* opCtx, Collection* collection); +void createSystemIndexes(OperationContext* opCtx, const Collection* collection); /** * Verifies that only the appropriate indexes to support authentication, authorization, and diff --git a/src/mongo/db/ttl.cpp b/src/mongo/db/ttl.cpp index f99a991da20..dec5e29350a 100644 --- a/src/mongo/db/ttl.cpp +++ b/src/mongo/db/ttl.cpp @@ -212,8 +212,7 @@ private: continue; } - AutoGetCollection autoColl(&opCtx, *nss, MODE_IS); - Collection* coll = autoColl.getCollection(); + AutoGetCollection coll(&opCtx, *nss, MODE_IS); // The collection with `uuid` might be renamed before the lock and the wrong // namespace would be locked and looked up so we double check here. if (!coll || coll->uuid() != uuid) @@ -296,14 +295,12 @@ private: "key"_attr = key, "name"_attr = name); - AutoGetCollection autoGetCollection(opCtx, collectionNSS, MODE_IX); + AutoGetCollection collection(opCtx, collectionNSS, MODE_IX); if (MONGO_unlikely(hangTTLMonitorWithLock.shouldFail())) { LOGV2(22534, "Hanging due to hangTTLMonitorWithLock fail point"); hangTTLMonitorWithLock.pauseWhileSet(opCtx); } - - Collection* collection = autoGetCollection.getCollection(); if (!collection) { // Collection was dropped. return; @@ -375,7 +372,7 @@ private: auto exec = InternalPlanner::deleteWithIndexScan(opCtx, - collection, + collection.getCollection(), std::move(params), desc, startKey, diff --git a/src/mongo/db/views/durable_view_catalog.cpp b/src/mongo/db/views/durable_view_catalog.cpp index 806e6e8d87e..d27b4384a59 100644 --- a/src/mongo/db/views/durable_view_catalog.cpp +++ b/src/mongo/db/views/durable_view_catalog.cpp @@ -111,7 +111,7 @@ void DurableViewCatalogImpl::_iterate(OperationContext* opCtx, ViewCatalogLookupBehavior lookupBehavior) { invariant(opCtx->lockState()->isCollectionLockedForMode(_db->getSystemViewsName(), MODE_IS)); - Collection* systemViews = + const Collection* systemViews = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, _db->getSystemViewsName()); if (!systemViews) { return; @@ -186,7 +186,7 @@ void DurableViewCatalogImpl::upsert(OperationContext* opCtx, NamespaceString systemViewsNs(_db->getSystemViewsName()); dassert(opCtx->lockState()->isCollectionLockedForMode(systemViewsNs, MODE_X)); - Collection* systemViews = + const Collection* systemViews = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, systemViewsNs); invariant(systemViews); @@ -218,7 +218,7 @@ void DurableViewCatalogImpl::remove(OperationContext* opCtx, const NamespaceStri dassert(opCtx->lockState()->isDbLockedForMode(_db->name(), MODE_IX)); dassert(opCtx->lockState()->isCollectionLockedForMode(name, MODE_IX)); - Collection* systemViews = + const Collection* systemViews = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, _db->getSystemViewsName()); dassert(opCtx->lockState()->isCollectionLockedForMode(systemViews->ns(), MODE_X)); diff --git a/src/mongo/dbtests/clienttests.cpp b/src/mongo/dbtests/clienttests.cpp index b007e2956ca..a8a42782b20 100644 --- a/src/mongo/dbtests/clienttests.cpp +++ b/src/mongo/dbtests/clienttests.cpp @@ -119,9 +119,9 @@ public: db.insert(ns(), BSON("x" << 1 << "y" << 2)); db.insert(ns(), BSON("x" << 2 << "y" << 2)); - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); ASSERT(collection); - IndexCatalog* indexCatalog = collection->getIndexCatalog(); + const IndexCatalog* indexCatalog = collection->getIndexCatalog(); const bool includeBuildUUIDs = false; const int options = 0; diff --git a/src/mongo/dbtests/counttests.cpp b/src/mongo/dbtests/counttests.cpp index 0506f843572..28734e0d9eb 100644 --- a/src/mongo/dbtests/counttests.cpp +++ b/src/mongo/dbtests/counttests.cpp @@ -52,7 +52,8 @@ public: WriteUnitOfWork wunit(&_opCtx); _collection = - CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); + CollectionCatalog::get(&_opCtx).lookupCollectionByNamespaceForMetadataWrite(&_opCtx, + nss()); if (_collection) { _database->dropCollection(&_opCtx, nss()).transitional_ignore(); } diff --git a/src/mongo/dbtests/dbtests.cpp b/src/mongo/dbtests/dbtests.cpp index 0ecc021f82d..67e1d45833e 100644 --- a/src/mongo/dbtests/dbtests.cpp +++ b/src/mongo/dbtests/dbtests.cpp @@ -105,8 +105,8 @@ Status createIndexFromSpec(OperationContext* opCtx, StringData ns, const BSONObj Collection* coll; { WriteUnitOfWork wunit(opCtx); - coll = - CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, NamespaceString(ns)); + coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite( + opCtx, NamespaceString(ns)); if (!coll) { coll = autoDb.getDb()->createCollection(opCtx, NamespaceString(ns)); } diff --git a/src/mongo/dbtests/dbtests.h b/src/mongo/dbtests/dbtests.h index 617a4f64520..8a1e7065573 100644 --- a/src/mongo/dbtests/dbtests.h +++ b/src/mongo/dbtests/dbtests.h @@ -79,7 +79,7 @@ public: return _clientContext->db(); } - Collection* getCollection() const { + const Collection* getCollection() const { return CollectionCatalog::get(_opCtx).lookupCollectionByNamespace(_opCtx, _nss); } diff --git a/src/mongo/dbtests/indexupdatetests.cpp b/src/mongo/dbtests/indexupdatetests.cpp index dc6f23cc99f..9ee7c081b1d 100644 --- a/src/mongo/dbtests/indexupdatetests.cpp +++ b/src/mongo/dbtests/indexupdatetests.cpp @@ -81,7 +81,8 @@ public: } Collection* collection() { - return CollectionCatalog::get(_opCtx).lookupCollectionByNamespace(_opCtx, _nss); + return CollectionCatalog::get(_opCtx).lookupCollectionByNamespaceForMetadataWrite(_opCtx, + _nss); } protected: diff --git a/src/mongo/dbtests/multikey_paths_test.cpp b/src/mongo/dbtests/multikey_paths_test.cpp index 5fcffe14b1d..0342a4049af 100644 --- a/src/mongo/dbtests/multikey_paths_test.cpp +++ b/src/mongo/dbtests/multikey_paths_test.cpp @@ -77,14 +77,14 @@ public: } } - Status createIndex(Collection* collection, BSONObj indexSpec) { + Status createIndex(const Collection* collection, BSONObj indexSpec) { return dbtests::createIndexFromSpec(_opCtx.get(), collection->ns().ns(), indexSpec); } - void assertMultikeyPaths(Collection* collection, + void assertMultikeyPaths(const Collection* collection, BSONObj keyPattern, const MultikeyPaths& expectedMultikeyPaths) { - IndexCatalog* indexCatalog = collection->getIndexCatalog(); + const IndexCatalog* indexCatalog = collection->getIndexCatalog(); std::vector<const IndexDescriptor*> indexes; indexCatalog->findIndexesByKeyPattern(_opCtx.get(), keyPattern, false, &indexes); ASSERT_EQ(indexes.size(), 1U); @@ -125,7 +125,7 @@ private: TEST_F(MultikeyPathsTest, PathsUpdatedOnIndexCreation) { AutoGetCollection autoColl(_opCtx.get(), _nss, MODE_X); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); invariant(collection); { @@ -150,7 +150,7 @@ TEST_F(MultikeyPathsTest, PathsUpdatedOnIndexCreation) { TEST_F(MultikeyPathsTest, PathsUpdatedOnIndexCreationWithMultipleDocuments) { AutoGetCollection autoColl(_opCtx.get(), _nss, MODE_X); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); invariant(collection); { @@ -179,7 +179,7 @@ TEST_F(MultikeyPathsTest, PathsUpdatedOnIndexCreationWithMultipleDocuments) { TEST_F(MultikeyPathsTest, PathsUpdatedOnDocumentInsert) { AutoGetCollection autoColl(_opCtx.get(), _nss, MODE_X); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); invariant(collection); BSONObj keyPattern = BSON("a" << 1 << "b" << 1); @@ -216,7 +216,7 @@ TEST_F(MultikeyPathsTest, PathsUpdatedOnDocumentInsert) { TEST_F(MultikeyPathsTest, PathsUpdatedOnDocumentUpdate) { AutoGetCollection autoColl(_opCtx.get(), _nss, MODE_X); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); invariant(collection); BSONObj keyPattern = BSON("a" << 1 << "b" << 1); @@ -264,7 +264,7 @@ TEST_F(MultikeyPathsTest, PathsUpdatedOnDocumentUpdate) { TEST_F(MultikeyPathsTest, PathsNotUpdatedOnDocumentDelete) { AutoGetCollection autoColl(_opCtx.get(), _nss, MODE_X); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); invariant(collection); BSONObj keyPattern = BSON("a" << 1 << "b" << 1); @@ -304,7 +304,7 @@ TEST_F(MultikeyPathsTest, PathsNotUpdatedOnDocumentDelete) { TEST_F(MultikeyPathsTest, PathsUpdatedForMultipleIndexesOnDocumentInsert) { AutoGetCollection autoColl(_opCtx.get(), _nss, MODE_X); - Collection* collection = autoColl.getCollection(); + const Collection* collection = autoColl.getCollection(); invariant(collection); BSONObj keyPatternAB = BSON("a" << 1 << "b" << 1); diff --git a/src/mongo/dbtests/pdfiletests.cpp b/src/mongo/dbtests/pdfiletests.cpp index ac55a11f63b..2352931aa9e 100644 --- a/src/mongo/dbtests/pdfiletests.cpp +++ b/src/mongo/dbtests/pdfiletests.cpp @@ -59,7 +59,7 @@ protected: static NamespaceString nss() { return NamespaceString("unittests.pdfiletests.Insert"); } - Collection* collection() { + const Collection* collection() { return CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); } @@ -75,7 +75,7 @@ public: WriteUnitOfWork wunit(&_opCtx); BSONObj x = BSON("x" << 1); ASSERT(x["_id"].type() == 0); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { coll = _context.db()->createCollection(&_opCtx, nss()); diff --git a/src/mongo/dbtests/plan_executor_invalidation_test.cpp b/src/mongo/dbtests/plan_executor_invalidation_test.cpp index 8ff34319036..7b65c5cc1b3 100644 --- a/src/mongo/dbtests/plan_executor_invalidation_test.cpp +++ b/src/mongo/dbtests/plan_executor_invalidation_test.cpp @@ -118,7 +118,8 @@ public: } Collection* collection() { - return CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss); + return CollectionCatalog::get(&_opCtx).lookupCollectionByNamespaceForMetadataWrite(&_opCtx, + nss); } void truncateCollection(Collection* collection) const { diff --git a/src/mongo/dbtests/query_plan_executor.cpp b/src/mongo/dbtests/query_plan_executor.cpp index 075ededc8e9..d0bc883c9d5 100644 --- a/src/mongo/dbtests/query_plan_executor.cpp +++ b/src/mongo/dbtests/query_plan_executor.cpp @@ -97,7 +97,7 @@ public: * capable of executing a simple collection scan. */ unique_ptr<PlanExecutor, PlanExecutor::Deleter> makeCollScanExec( - Collection* coll, + const Collection* coll, BSONObj& filterObj, PlanYieldPolicy::YieldPolicy yieldPolicy = PlanYieldPolicy::YieldPolicy::YIELD_MANUAL, TailableModeEnum tailableMode = TailableModeEnum::kNormal) { @@ -183,7 +183,7 @@ protected: private: const IndexDescriptor* getIndex(Database* db, const BSONObj& obj) { - Collection* collection = + const Collection* collection = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss); std::vector<const IndexDescriptor*> indexes; collection->getIndexCatalog()->findIndexesByKeyPattern(&_opCtx, obj, false, &indexes); @@ -206,7 +206,7 @@ TEST_F(PlanExecutorTest, DropIndexScanAgg) { BSONObj indexSpec = BSON("a" << 1); addIndex(indexSpec); - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); // Create the aggregation pipeline. std::vector<BSONObj> rawPipeline = {fromjson("{$match: {a: {$gte: 7, $lte: 10}}}")}; @@ -242,7 +242,7 @@ TEST_F(PlanExecutorTest, ShouldReportErrorIfExceedsTimeLimitDuringYield) { BSONObj filterObj = fromjson("{_id: {$gt: 0}}"); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); auto exec = makeCollScanExec(coll, filterObj, PlanYieldPolicy::YieldPolicy::ALWAYS_TIME_OUT); BSONObj resultObj; @@ -259,7 +259,7 @@ TEST_F(PlanExecutorTest, ShouldReportErrorIfKilledDuringYieldButIsTailableAndAwa BSONObj filterObj = fromjson("{_id: {$gt: 0}}"); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); auto exec = makeCollScanExec(coll, filterObj, PlanYieldPolicy::YieldPolicy::ALWAYS_TIME_OUT, @@ -279,7 +279,7 @@ TEST_F(PlanExecutorTest, ShouldNotSwallowExceedsTimeLimitDuringYieldButIsTailabl BSONObj filterObj = fromjson("{_id: {$gt: 0}}"); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); auto exec = makeCollScanExec(coll, filterObj, PlanYieldPolicy::YieldPolicy::ALWAYS_TIME_OUT, @@ -299,7 +299,7 @@ TEST_F(PlanExecutorTest, ShouldReportErrorIfKilledDuringYield) { BSONObj filterObj = fromjson("{_id: {$gt: 0}}"); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); auto exec = makeCollScanExec(coll, filterObj, PlanYieldPolicy::YieldPolicy::ALWAYS_MARK_KILLED); BSONObj resultObj; @@ -364,7 +364,7 @@ TEST_F(PlanExecutorSnapshotTest, SnapshotControl) { BSONObj filterObj = fromjson("{a: {$gte: 2}}"); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); auto exec = makeCollScanExec(coll, filterObj); BSONObj objOut; diff --git a/src/mongo/dbtests/query_stage_and.cpp b/src/mongo/dbtests/query_stage_and.cpp index 96dac1ea2e5..d08909af1ce 100644 --- a/src/mongo/dbtests/query_stage_and.cpp +++ b/src/mongo/dbtests/query_stage_and.cpp @@ -73,7 +73,7 @@ public: ASSERT_OK(dbtests::createIndex(&_opCtx, ns(), obj)); } - const IndexDescriptor* getIndex(const BSONObj& obj, Collection* coll) { + const IndexDescriptor* getIndex(const BSONObj& obj, const Collection* coll) { std::vector<const IndexDescriptor*> indexes; coll->getIndexCatalog()->findIndexesByKeyPattern(&_opCtx, obj, false, &indexes); if (indexes.empty()) { @@ -92,7 +92,7 @@ public: return params; } - void getRecordIds(set<RecordId>* out, Collection* coll) { + void getRecordIds(set<RecordId>* out, const Collection* coll) { auto cursor = coll->getCursor(&_opCtx); while (auto record = cursor->next()) { out->insert(record->id); @@ -178,7 +178,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -264,7 +264,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -345,7 +345,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -389,7 +389,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -437,7 +437,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -483,7 +483,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -536,7 +536,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -589,7 +589,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -645,7 +645,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -693,7 +693,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -746,7 +746,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -796,7 +796,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -918,7 +918,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -1026,7 +1026,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -1080,7 +1080,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -1119,7 +1119,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -1162,7 +1162,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -1223,7 +1223,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); @@ -1276,7 +1276,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); if (!coll) { WriteUnitOfWork wuow(&_opCtx); coll = db->createCollection(&_opCtx, nss()); diff --git a/src/mongo/dbtests/query_stage_cached_plan.cpp b/src/mongo/dbtests/query_stage_cached_plan.cpp index cf38ceadda4..cc62d39971b 100644 --- a/src/mongo/dbtests/query_stage_cached_plan.cpp +++ b/src/mongo/dbtests/query_stage_cached_plan.cpp @@ -81,7 +81,7 @@ public: addIndex(BSON("b" << 1)); dbtests::WriteContextForTests ctx(&_opCtx, nss.ns()); - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); ASSERT(collection); // Add data. @@ -111,7 +111,7 @@ public: wuow.commit(); } - void insertDocument(Collection* collection, BSONObj obj) { + void insertDocument(const Collection* collection, BSONObj obj) { WriteUnitOfWork wuow(&_opCtx); OpDebug* const nullOpDebug = nullptr; diff --git a/src/mongo/dbtests/query_stage_collscan.cpp b/src/mongo/dbtests/query_stage_collscan.cpp index 275f13f5158..e765f7473a7 100644 --- a/src/mongo/dbtests/query_stage_collscan.cpp +++ b/src/mongo/dbtests/query_stage_collscan.cpp @@ -247,7 +247,7 @@ TEST_F(QueryStageCollectionScanTest, QueryStageCollscanObjectsInOrderBackward) { TEST_F(QueryStageCollectionScanTest, QueryStageCollscanDeleteUpcomingObject) { dbtests::WriteContextForTests ctx(&_opCtx, nss.ns()); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); // Get the RecordIds that would be returned by an in-order scan. vector<RecordId> recordIds; @@ -300,7 +300,7 @@ TEST_F(QueryStageCollectionScanTest, QueryStageCollscanDeleteUpcomingObject) { // object we would have gotten after that. But, do it in reverse! TEST_F(QueryStageCollectionScanTest, QueryStageCollscanDeleteUpcomingObjectBackward) { dbtests::WriteContextForTests ctx(&_opCtx, nss.ns()); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); // Get the RecordIds that would be returned by an in-order scan. vector<RecordId> recordIds; diff --git a/src/mongo/dbtests/query_stage_delete.cpp b/src/mongo/dbtests/query_stage_delete.cpp index 6ff9419dd17..b362e23516f 100644 --- a/src/mongo/dbtests/query_stage_delete.cpp +++ b/src/mongo/dbtests/query_stage_delete.cpp @@ -81,7 +81,7 @@ public: _client.remove(nss.ns(), obj); } - void getRecordIds(Collection* collection, + void getRecordIds(const Collection* collection, CollectionScanParams::Direction direction, vector<RecordId>* out) { WorkingSet ws; @@ -133,7 +133,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, nss.ns()); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); ASSERT(coll); // Get the RecordIds that would be returned by an in-order scan. @@ -194,7 +194,7 @@ public: void run() { // Various variables we'll need. dbtests::WriteContextForTests ctx(&_opCtx, nss.ns()); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); ASSERT(coll); const int targetDocIndex = 0; const BSONObj query = BSON("foo" << BSON("$gte" << targetDocIndex)); diff --git a/src/mongo/dbtests/query_stage_fetch.cpp b/src/mongo/dbtests/query_stage_fetch.cpp index 163621ce89e..4d040923e34 100644 --- a/src/mongo/dbtests/query_stage_fetch.cpp +++ b/src/mongo/dbtests/query_stage_fetch.cpp @@ -62,7 +62,7 @@ public: _client.dropCollection(ns()); } - void getRecordIds(set<RecordId>* out, Collection* coll) { + void getRecordIds(set<RecordId>* out, const Collection* coll) { auto cursor = coll->getCursor(&_opCtx); while (auto record = cursor->next()) { out->insert(record->id); @@ -102,7 +102,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -169,7 +169,7 @@ public: Lock::DBLock lk(&_opCtx, nss().db(), MODE_X); OldClientContext ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); diff --git a/src/mongo/dbtests/query_stage_merge_sort.cpp b/src/mongo/dbtests/query_stage_merge_sort.cpp index f645dc88d07..2e386c1b114 100644 --- a/src/mongo/dbtests/query_stage_merge_sort.cpp +++ b/src/mongo/dbtests/query_stage_merge_sort.cpp @@ -72,7 +72,7 @@ public: ASSERT_OK(dbtests::createIndex(&_opCtx, ns(), obj)); } - const IndexDescriptor* getIndex(const BSONObj& obj, Collection* coll) { + const IndexDescriptor* getIndex(const BSONObj& obj, const Collection* coll) { std::vector<const IndexDescriptor*> indexes; coll->getIndexCatalog()->findIndexesByKeyPattern(&_opCtx, obj, false, &indexes); return indexes.empty() ? nullptr : indexes[0]; @@ -101,7 +101,7 @@ public: _client.update(ns(), predicate, update); } - void getRecordIds(set<RecordId>* out, Collection* coll) { + void getRecordIds(set<RecordId>* out, const Collection* coll) { auto cursor = coll->getCursor(&_opCtx); while (auto record = cursor->next()) { out->insert(record->id); @@ -148,7 +148,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -218,7 +218,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -287,7 +287,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -357,7 +357,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -431,7 +431,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -499,7 +499,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -557,7 +557,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -677,7 +677,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -780,7 +780,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -852,7 +852,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); diff --git a/src/mongo/dbtests/query_stage_sort.cpp b/src/mongo/dbtests/query_stage_sort.cpp index bf3353d698b..6b09933f62a 100644 --- a/src/mongo/dbtests/query_stage_sort.cpp +++ b/src/mongo/dbtests/query_stage_sort.cpp @@ -76,7 +76,7 @@ public: _client.insert(ns(), obj); } - void getRecordIds(set<RecordId>* out, Collection* coll) { + void getRecordIds(set<RecordId>* out, const Collection* coll) { auto cursor = coll->getCursor(&_opCtx); while (auto record = cursor->next()) { out->insert(record->id); @@ -86,7 +86,7 @@ public: /** * We feed a mix of (key, unowned, owned) data to the sort stage. */ - void insertVarietyOfObjects(WorkingSet* ws, QueuedDataStage* ms, Collection* coll) { + void insertVarietyOfObjects(WorkingSet* ws, QueuedDataStage* ms, const Collection* coll) { set<RecordId> recordIds; getRecordIds(&recordIds, coll); @@ -111,7 +111,7 @@ public: * which is owned by the caller. */ unique_ptr<PlanExecutor, PlanExecutor::Deleter> makePlanExecutorWithSortStage( - Collection* coll) { + const Collection* coll) { // Build the mock scan stage which feeds the data. auto ws = std::make_unique<WorkingSet>(); _workingSet = ws.get(); @@ -152,7 +152,7 @@ public: * If extAllowed is true, sorting will use use external sorting if available. * If limit is not zero, we limit the output of the sort stage to 'limit' results. */ - void sortAndCheck(int direction, Collection* coll) { + void sortAndCheck(int direction, const Collection* coll) { auto ws = std::make_unique<WorkingSet>(); auto queuedDataStage = std::make_unique<QueuedDataStage>(_expCtx.get(), ws.get()); @@ -259,7 +259,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -282,7 +282,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -314,7 +314,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -340,7 +340,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -455,7 +455,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); @@ -559,7 +559,7 @@ public: void run() { dbtests::WriteContextForTests ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wuow(&_opCtx); diff --git a/src/mongo/dbtests/query_stage_subplan.cpp b/src/mongo/dbtests/query_stage_subplan.cpp index 8d56d4e094d..51c00d629b8 100644 --- a/src/mongo/dbtests/query_stage_subplan.cpp +++ b/src/mongo/dbtests/query_stage_subplan.cpp @@ -139,7 +139,7 @@ TEST_F(QueryStageSubplanTest, QueryStageSubplanGeo2dOr) { ASSERT_OK(statusWithCQ.getStatus()); std::unique_ptr<CanonicalQuery> cq = std::move(statusWithCQ.getValue()); - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); // Get planner params. QueryPlannerParams plannerParams; @@ -168,7 +168,7 @@ void assertSubplanFromCache(QueryStageSubplanTest* test, const dbtests::WriteCon test->insert(BSON("a" << 1 << "b" << i << "c" << i)); } - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); auto qr = std::make_unique<QueryRequest>(nss); qr->setFilter(query); @@ -252,7 +252,7 @@ TEST_F(QueryStageSubplanTest, QueryStageSubplanDontCacheZeroResults) { // one relevant index. BSONObj query = fromjson("{$or: [{a: 1, b: 15}, {c: 1}]}"); - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); auto qr = std::make_unique<QueryRequest>(nss); qr->setFilter(query); @@ -308,7 +308,7 @@ TEST_F(QueryStageSubplanTest, QueryStageSubplanDontCacheTies) { // ranking. For the second branch it's because there is only one relevant index. BSONObj query = fromjson("{$or: [{a: 1, e: 1}, {d: 1}]}"); - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); auto qr = std::make_unique<QueryRequest>(nss); qr->setFilter(query); @@ -487,7 +487,7 @@ TEST_F(QueryStageSubplanTest, QueryStageSubplanPlanRootedOrNE) { qr->setSort(BSON("d" << 1)); auto cq = unittest::assertGet(CanonicalQuery::canonicalize(opCtx(), std::move(qr))); - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); QueryPlannerParams plannerParams; fillOutPlannerParams(opCtx(), collection, cq.get(), &plannerParams); @@ -571,7 +571,7 @@ TEST_F(QueryStageSubplanTest, ShouldReportErrorIfKilledDuringPlanning) { } TEST_F(QueryStageSubplanTest, ShouldThrowOnRestoreIfIndexDroppedBeforePlanSelection) { - Collection* collection = nullptr; + const Collection* collection = nullptr; { dbtests::WriteContextForTests ctx{opCtx(), nss.ns()}; addIndex(BSON("p1" << 1 << "opt1" << 1)); @@ -615,7 +615,7 @@ TEST_F(QueryStageSubplanTest, ShouldThrowOnRestoreIfIndexDroppedBeforePlanSelect } TEST_F(QueryStageSubplanTest, ShouldNotThrowOnRestoreIfIndexDroppedAfterPlanSelection) { - Collection* collection = nullptr; + const Collection* collection = nullptr; { dbtests::WriteContextForTests ctx{opCtx(), nss.ns()}; addIndex(BSON("p1" << 1 << "opt1" << 1)); diff --git a/src/mongo/dbtests/query_stage_update.cpp b/src/mongo/dbtests/query_stage_update.cpp index e1e01a3d008..439531d9ff9 100644 --- a/src/mongo/dbtests/query_stage_update.cpp +++ b/src/mongo/dbtests/query_stage_update.cpp @@ -204,7 +204,7 @@ public: CurOp& curOp = *CurOp::get(_opCtx); OpDebug* opDebug = &curOp.debug(); UpdateDriver driver(_expCtx); - Collection* collection = ctx.getCollection(); + const Collection* collection = ctx.getCollection(); ASSERT(collection); // Collection should be empty. @@ -276,7 +276,7 @@ public: CurOp& curOp = *CurOp::get(_opCtx); OpDebug* opDebug = &curOp.debug(); UpdateDriver driver(_expCtx); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss); ASSERT(coll); @@ -388,7 +388,7 @@ public: // Various variables we'll need. dbtests::WriteContextForTests ctx(&_opCtx, nss.ns()); OpDebug* opDebug = &CurOp::get(_opCtx)->debug(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); ASSERT(coll); auto request = UpdateRequest(); request.setNamespaceString(nss); @@ -481,7 +481,7 @@ public: // Various variables we'll need. dbtests::WriteContextForTests ctx(&_opCtx, nss.ns()); OpDebug* opDebug = &CurOp::get(_opCtx)->debug(); - Collection* coll = ctx.getCollection(); + const Collection* coll = ctx.getCollection(); ASSERT(coll); auto request = UpdateRequest(); request.setNamespaceString(nss); diff --git a/src/mongo/dbtests/querytests.cpp b/src/mongo/dbtests/querytests.cpp index fbda40e576a..84d533e2069 100644 --- a/src/mongo/dbtests/querytests.cpp +++ b/src/mongo/dbtests/querytests.cpp @@ -69,7 +69,8 @@ public: WriteUnitOfWork wunit(&_opCtx); _database = _context.db(); _collection = - CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); + CollectionCatalog::get(&_opCtx).lookupCollectionByNamespaceForMetadataWrite(&_opCtx, + nss()); if (_collection) { _database->dropCollection(&_opCtx, nss()).transitional_ignore(); } diff --git a/src/mongo/dbtests/repltests.cpp b/src/mongo/dbtests/repltests.cpp index a9cd656c0e9..e35d43f9a42 100644 --- a/src/mongo/dbtests/repltests.cpp +++ b/src/mongo/dbtests/repltests.cpp @@ -128,7 +128,8 @@ public: dbtests::WriteContextForTests ctx(&_opCtx, ns()); WriteUnitOfWork wuow(&_opCtx); - Collection* c = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); + const Collection* c = + CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!c) { c = ctx.db()->createCollection(&_opCtx, nss()); } @@ -200,7 +201,7 @@ protected: Lock::GlobalWrite lk(&_opCtx); OldClientContext ctx(&_opCtx, ns()); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { WriteUnitOfWork wunit(&_opCtx); @@ -259,7 +260,8 @@ protected: WriteUnitOfWork wunit(&_opCtx); Database* db = ctx.db(); Collection* coll = - CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss); + CollectionCatalog::get(&_opCtx).lookupCollectionByNamespaceForMetadataWrite(&_opCtx, + nss); if (!coll) { coll = db->createCollection(&_opCtx, nss); } @@ -273,7 +275,7 @@ protected: OldClientContext ctx(&_opCtx, ns()); WriteUnitOfWork wunit(&_opCtx); Database* db = ctx.db(); - Collection* coll = + const Collection* coll = CollectionCatalog::get(&_opCtx).lookupCollectionByNamespace(&_opCtx, nss()); if (!coll) { coll = db->createCollection(&_opCtx, nss()); diff --git a/src/mongo/dbtests/rollbacktests.cpp b/src/mongo/dbtests/rollbacktests.cpp index ebd8ce2e5cb..1b86b7a319b 100644 --- a/src/mongo/dbtests/rollbacktests.cpp +++ b/src/mongo/dbtests/rollbacktests.cpp @@ -84,7 +84,8 @@ Status renameCollection(OperationContext* opCtx, return renameCollection(opCtx, source, target, {}); } Status truncateCollection(OperationContext* opCtx, const NamespaceString& nss) { - auto coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); + auto coll = + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, nss); return coll->truncate(opCtx); } @@ -121,7 +122,7 @@ size_t getNumIndexEntries(OperationContext* opCtx, size_t numEntries = 0; auto coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); - IndexCatalog* catalog = coll->getIndexCatalog(); + const IndexCatalog* catalog = coll->getIndexCatalog(); auto desc = catalog->findIndexByName(opCtx, idxName, false); if (desc) { @@ -142,7 +143,8 @@ size_t getNumIndexEntries(OperationContext* opCtx, } void dropIndex(OperationContext* opCtx, const NamespaceString& nss, const string& idxName) { - auto coll = CollectionCatalog::get(opCtx).lookupCollectionByNamespace(opCtx, nss); + auto coll = + CollectionCatalog::get(opCtx).lookupCollectionByNamespaceForMetadataWrite(opCtx, nss); auto desc = coll->getIndexCatalog()->findIndexByName(opCtx, idxName); ASSERT(desc); ASSERT_OK(coll->getIndexCatalog()->dropIndex(opCtx, desc)); @@ -485,7 +487,8 @@ public: AutoGetDb autoDb(&opCtx, nss.db(), MODE_X); - Collection* coll = CollectionCatalog::get(&opCtx).lookupCollectionByNamespace(&opCtx, nss); + Collection* coll = + CollectionCatalog::get(&opCtx).lookupCollectionByNamespaceForMetadataWrite(&opCtx, nss); IndexCatalog* catalog = coll->getIndexCatalog(); string idxName = "a"; @@ -526,7 +529,8 @@ public: AutoGetDb autoDb(&opCtx, nss.db(), MODE_X); - Collection* coll = CollectionCatalog::get(&opCtx).lookupCollectionByNamespace(&opCtx, nss); + Collection* coll = + CollectionCatalog::get(&opCtx).lookupCollectionByNamespaceForMetadataWrite(&opCtx, nss); IndexCatalog* catalog = coll->getIndexCatalog(); string idxName = "a"; @@ -579,7 +583,8 @@ public: AutoGetDb autoDb(&opCtx, nss.db(), MODE_X); - Collection* coll = CollectionCatalog::get(&opCtx).lookupCollectionByNamespace(&opCtx, nss); + Collection* coll = + CollectionCatalog::get(&opCtx).lookupCollectionByNamespaceForMetadataWrite(&opCtx, nss); IndexCatalog* catalog = coll->getIndexCatalog(); string idxName = "a"; @@ -643,7 +648,8 @@ public: ASSERT_OK(ctx.db()->userCreateNS(&opCtx, nss, collectionOptions, false)); ASSERT(collectionExists(&opCtx, &ctx, nss.ns())); Collection* coll = - CollectionCatalog::get(&opCtx).lookupCollectionByNamespace(&opCtx, nss); + CollectionCatalog::get(&opCtx).lookupCollectionByNamespaceForMetadataWrite(&opCtx, + nss); IndexCatalog* catalog = coll->getIndexCatalog(); ASSERT_OK(catalog->createIndexOnEmptyCollection(&opCtx, specA)); diff --git a/src/mongo/dbtests/storage_timestamp_tests.cpp b/src/mongo/dbtests/storage_timestamp_tests.cpp index 32656e03b7d..750c8ac447d 100644 --- a/src/mongo/dbtests/storage_timestamp_tests.cpp +++ b/src/mongo/dbtests/storage_timestamp_tests.cpp @@ -237,13 +237,13 @@ public: _opCtx->recoveryUnit()->setTimestampReadSource(RecoveryUnit::ReadSource::kUnset); AutoGetCollection collRaii(_opCtx, nss, LockMode::MODE_X); - if (collRaii.getCollection()) { + if (collRaii) { WriteUnitOfWork wunit(_opCtx); - invariant(collRaii.getCollection()->truncate(_opCtx).isOK()); + invariant(collRaii.getWritableCollection()->truncate(_opCtx).isOK()); if (_opCtx->recoveryUnit()->getCommitTimestamp().isNull()) { ASSERT_OK(_opCtx->recoveryUnit()->setTimestamp(Timestamp(1, 1))); } - collRaii.getCollection()->getIndexCatalog()->dropAllIndexes(_opCtx, false); + collRaii.getWritableCollection()->getIndexCatalog()->dropAllIndexes(_opCtx, false); wunit.commit(); return; } @@ -258,7 +258,7 @@ public: }); } - void insertDocument(Collection* coll, const InsertStatement& stmt) { + void insertDocument(const Collection* coll, const InsertStatement& stmt) { // Insert some documents. OpDebug* const nullOpDebug = nullptr; const bool fromMigrate = false; @@ -383,7 +383,7 @@ public: const Timestamp& ts, const repl::MinValidDocument& expectedDoc) { AutoGetCollection autoColl(_opCtx, nss, LockMode::MODE_IX); - Collection* coll = autoColl.getCollection(); + const Collection* coll = autoColl.getCollection(); OneOffRead oor(_opCtx, ts); @@ -667,7 +667,7 @@ public: } void assertMultikeyPaths(OperationContext* opCtx, - Collection* collection, + const Collection* collection, StringData indexName, Timestamp ts, bool shouldBeMultikey, @@ -1891,7 +1891,7 @@ public: MultiIndexBlock indexer; auto abortOnExit = makeGuard([&] { indexer.abortIndexBuild( - _opCtx, autoColl.getCollection(), MultiIndexBlock::kNoopOnCleanUpFn); + _opCtx, autoColl.getWritableCollection(), MultiIndexBlock::kNoopOnCleanUpFn); }); const LogicalTime beforeIndexBuild = _clock->tickClusterTime(2); BSONObj indexInfoObj; @@ -1910,7 +1910,7 @@ public: auto swIndexInfoObj = indexer.init( _opCtx, - autoColl.getCollection(), + autoColl.getWritableCollection(), {BSON("v" << 2 << "unique" << true << "name" << "a_1" << "key" << BSON("a" << 1))}, @@ -1933,7 +1933,7 @@ public: // timestamp. ASSERT_OK(indexer.commit( _opCtx, - autoColl.getCollection(), + autoColl.getWritableCollection(), [&](const BSONObj& indexSpec) { if (SimulatePrimary) { // The timestamping responsibility for each index is placed on the caller. @@ -2005,7 +2005,7 @@ public: MultiIndexBlock indexer; auto abortOnExit = makeGuard([&] { indexer.abortIndexBuild( - _opCtx, autoColl.getCollection(), MultiIndexBlock::kNoopOnCleanUpFn); + _opCtx, autoColl.getWritableCollection(), MultiIndexBlock::kNoopOnCleanUpFn); }); const LogicalTime beforeIndexBuild = _clock->tickClusterTime(2); BSONObj indexInfoObj; @@ -2024,7 +2024,7 @@ public: auto swIndexInfoObj = indexer.init( _opCtx, - autoColl.getCollection(), + autoColl.getWritableCollection(), {BSON("v" << 2 << "unique" << true << "name" << "a_1" << "ns" << nss.ns() << "key" << BSON("a" << 1))}, @@ -2516,7 +2516,8 @@ public: std::vector<std::string> indexIdents; // Create an index and get the ident for each index. for (auto key : {"a", "b", "c"}) { - createIndex(autoColl.getCollection(), str::stream() << key << "_1", BSON(key << 1)); + createIndex( + autoColl.getWritableCollection(), str::stream() << key << "_1", BSON(key << 1)); // Timestamps at the completion of each index build. afterCreateTimestamps.push_back(_clock->tickClusterTime(1).asTimestamp()); @@ -2595,7 +2596,8 @@ public: std::vector<std::string> indexIdents; // Create an index and get the ident for each index. for (auto key : {"a", "b", "c"}) { - createIndex(autoColl.getCollection(), str::stream() << key << "_1", BSON(key << 1)); + createIndex( + autoColl.getWritableCollection(), str::stream() << key << "_1", BSON(key << 1)); // Timestamps at the completion of each index build. afterCreateTimestamps.push_back(_clock->tickClusterTime(1).asTimestamp()); @@ -2719,8 +2721,7 @@ public: NamespaceString nss("unittests.timestampIndexBuilds"); reset(nss); - AutoGetCollection autoColl(_opCtx, nss, LockMode::MODE_X); - auto collection = autoColl.getCollection(); + AutoGetCollection collection(_opCtx, nss, LockMode::MODE_X); // Indexing of parallel arrays is not allowed, so these are deemed "bad". const auto badDoc1 = @@ -2735,7 +2736,7 @@ public: { LOGV2(22505, "inserting {badDoc1}", "badDoc1"_attr = badDoc1); WriteUnitOfWork wuow(_opCtx); - insertDocument(autoColl.getCollection(), + insertDocument(collection.getCollection(), InsertStatement(badDoc1, insert1.asTimestamp(), presentTerm)); wuow.commit(); } @@ -2744,7 +2745,7 @@ public: { LOGV2(22506, "inserting {badDoc2}", "badDoc2"_attr = badDoc2); WriteUnitOfWork wuow(_opCtx); - insertDocument(autoColl.getCollection(), + insertDocument(collection.getCollection(), InsertStatement(badDoc2, insert2.asTimestamp(), presentTerm)); wuow.commit(); } @@ -2752,7 +2753,8 @@ public: const IndexCatalogEntry* buildingIndex = nullptr; MultiIndexBlock indexer; auto abortOnExit = makeGuard([&] { - indexer.abortIndexBuild(_opCtx, collection, MultiIndexBlock::kNoopOnCleanUpFn); + indexer.abortIndexBuild( + _opCtx, collection.getWritableCollection(), MultiIndexBlock::kNoopOnCleanUpFn); }); // Provide a build UUID, indicating that this is a two-phase index build. @@ -2770,14 +2772,14 @@ public: { TimestampBlock tsBlock(_opCtx, indexInit.asTimestamp()); - auto swSpecs = - indexer.init(_opCtx, - collection, - {BSON("v" << 2 << "name" - << "a_1_b_1" - << "ns" << collection->ns().ns() << "key" - << BSON("a" << 1 << "b" << 1))}, - MultiIndexBlock::makeTimestampedIndexOnInitFn(_opCtx, collection)); + auto swSpecs = indexer.init(_opCtx, + collection.getWritableCollection(), + {BSON("v" << 2 << "name" + << "a_1_b_1" + << "ns" << collection->ns().ns() << "key" + << BSON("a" << 1 << "b" << 1))}, + MultiIndexBlock::makeTimestampedIndexOnInitFn( + _opCtx, collection.getCollection())); ASSERT_OK(swSpecs.getStatus()); } @@ -2786,7 +2788,7 @@ public: indexCatalog->findIndexByName(_opCtx, "a_1_b_1", /* includeUnfinished */ true)); ASSERT(buildingIndex); - ASSERT_OK(indexer.insertAllDocumentsInCollection(_opCtx, collection)); + ASSERT_OK(indexer.insertAllDocumentsInCollection(_opCtx, collection.getCollection())); ASSERT_TRUE(buildingIndex->indexBuildInterceptor()->areAllWritesApplied(_opCtx)); @@ -2820,7 +2822,7 @@ public: buildingIndex->indexBuildInterceptor()->getSkippedRecordTracker()->areAllRecordsApplied( _opCtx)); // This fails because the bad record is still invalid. - auto status = indexer.retrySkippedRecords(_opCtx, collection); + auto status = indexer.retrySkippedRecords(_opCtx, collection.getCollection()); ASSERT_EQ(status.code(), ErrorCodes::CannotIndexParallelArrays); ASSERT_FALSE( @@ -2832,8 +2834,8 @@ public: // to the side writes table and must be drained. Helpers::upsert(_opCtx, collection->ns().ns(), BSON("_id" << 0 << "a" << 1 << "b" << 1)); { - RecordId badRecord = - Helpers::findOne(_opCtx, collection, BSON("_id" << 1), false /* requireIndex */); + RecordId badRecord = Helpers::findOne( + _opCtx, collection.getCollection(), BSON("_id" << 1), false /* requireIndex */); WriteUnitOfWork wuow(_opCtx); collection->deleteDocument(_opCtx, kUninitializedStmtId, badRecord, nullptr); wuow.commit(); @@ -2846,7 +2848,7 @@ public: // This succeeds because the bad documents are now either valid or removed. - ASSERT_OK(indexer.retrySkippedRecords(_opCtx, collection)); + ASSERT_OK(indexer.retrySkippedRecords(_opCtx, collection.getCollection())); ASSERT_TRUE( buildingIndex->indexBuildInterceptor()->getSkippedRecordTracker()->areAllRecordsApplied( _opCtx)); @@ -2857,7 +2859,7 @@ public: WriteUnitOfWork wuow(_opCtx); ASSERT_OK(indexer.commit( _opCtx, - collection, + collection.getWritableCollection(), [&](const BSONObj& indexSpec) { _opCtx->getServiceContext()->getOpObserver()->onCreateIndex( _opCtx, collection->ns(), collection->uuid(), indexSpec, false); diff --git a/src/mongo/dbtests/validate_tests.cpp b/src/mongo/dbtests/validate_tests.cpp index be56190e176..df29527f5f7 100644 --- a/src/mongo/dbtests/validate_tests.cpp +++ b/src/mongo/dbtests/validate_tests.cpp @@ -194,7 +194,7 @@ public: // Create a new collection, insert records {_id: 1} and {_id: 2} and check it's valid. lockDb(MODE_X); - Collection* coll; + const Collection* coll; RecordId id1; { OpDebug* const nullOpDebug = nullptr; @@ -256,7 +256,7 @@ public: // Create a new collection, insert two documents. lockDb(MODE_X); - Collection* coll; + const Collection* coll; RecordId id1; { OpDebug* const nullOpDebug = nullptr; @@ -328,7 +328,7 @@ public: // Create a new collection, insert three records. lockDb(MODE_X); OpDebug* const nullOpDebug = nullptr; - Collection* coll; + const Collection* coll; RecordId id1; { WriteUnitOfWork wunit(&_opCtx); @@ -391,7 +391,7 @@ public: // Create a new collection, insert records {_id: 1} and {_id: 2} and check it's valid. lockDb(MODE_X); OpDebug* const nullOpDebug = nullptr; - Collection* coll; + const Collection* coll; RecordId id1; { WriteUnitOfWork wunit(&_opCtx); @@ -471,7 +471,7 @@ public: // Create a new collection, insert three records and check it's valid. lockDb(MODE_X); OpDebug* const nullOpDebug = nullptr; - Collection* coll; + const Collection* coll; RecordId id1; // {a: [b: 1, c: 2]}, {a: [b: 2, c: 2]}, {a: [b: 1, c: 1]} auto doc1 = BSON("_id" << 1 << "a" << BSON_ARRAY(BSON("b" << 1) << BSON("c" << 2))); @@ -557,7 +557,7 @@ public: // Create a new collection, insert three records and check it's valid. lockDb(MODE_X); OpDebug* const nullOpDebug = nullptr; - Collection* coll; + const Collection* coll; RecordId id1; { WriteUnitOfWork wunit(&_opCtx); @@ -621,7 +621,7 @@ public: // Create a new collection, insert three records and check it's valid. lockDb(MODE_X); OpDebug* const nullOpDebug = nullptr; - Collection* coll; + const Collection* coll; RecordId id1; { WriteUnitOfWork wunit(&_opCtx); @@ -692,7 +692,7 @@ public: // field. lockDb(MODE_X); OpDebug* const nullOpDebug = nullptr; - Collection* coll; + const Collection* coll; RecordId id1; { WriteUnitOfWork wunit(&_opCtx); @@ -754,7 +754,7 @@ public: // Create a new collection, insert five records and check it's valid. lockDb(MODE_X); OpDebug* const nullOpDebug = nullptr; - Collection* coll; + const Collection* coll; RecordId id1; { WriteUnitOfWork wunit(&_opCtx); @@ -839,7 +839,7 @@ public: // Create a new collection, insert three records and check it's valid. lockDb(MODE_X); OpDebug* const nullOpDebug = nullptr; - Collection* coll; + const Collection* coll; RecordId id1; { WriteUnitOfWork wunit(&_opCtx); @@ -870,7 +870,7 @@ public: lockDb(MODE_X); // Replace a correct index entry with a bad one and check it's invalid. - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto iam = const_cast<IndexAccessMethod*>(indexCatalog->getEntry(descriptor)->accessMethod()); @@ -927,7 +927,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -987,7 +987,7 @@ public: // Insert additional multikey path metadata index keys. lockDb(MODE_X); const RecordId recordId(RecordId::ReservedId::kWildcardMultikeyMetadataId); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto accessMethod = const_cast<IndexAccessMethod*>(indexCatalog->getEntry(descriptor)->accessMethod()); @@ -1050,7 +1050,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -1106,7 +1106,7 @@ public: ensureValidateWorked(); lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto accessMethod = const_cast<IndexAccessMethod*>(indexCatalog->getEntry(descriptor)->accessMethod()); @@ -1148,7 +1148,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -1244,7 +1244,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -1285,7 +1285,7 @@ public: { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto iam = const_cast<IndexAccessMethod*>(indexCatalog->getEntry(descriptor)->accessMethod()); @@ -1361,7 +1361,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -1448,7 +1448,7 @@ public: void run() { // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -1629,7 +1629,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -1670,7 +1670,7 @@ public: { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto iam = const_cast<IndexAccessMethod*>(indexCatalog->getEntry(descriptor)->accessMethod()); @@ -1807,7 +1807,7 @@ public: void run() { // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -1962,7 +1962,7 @@ public: // Create a new collection and insert a document. lockDb(MODE_X); - Collection* coll; + const Collection* coll; OpDebug* const nullOpDebug = nullptr; { WriteUnitOfWork wunit(&_opCtx); @@ -2001,7 +2001,7 @@ public: { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); InsertDeleteOptions options; options.logIfError = true; @@ -2180,7 +2180,7 @@ public: // Create a new collection and insert non-multikey document. lockDb(MODE_X); - Collection* coll; + const Collection* coll; RecordId id1; BSONObj doc = BSON("_id" << 1 << "a" << 1); { @@ -2209,7 +2209,7 @@ public: // Set up a non-multikey index with multikey document. { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto iam = const_cast<IndexAccessMethod*>(indexCatalog->getEntry(descriptor)->accessMethod()); @@ -2358,7 +2358,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -2410,7 +2410,7 @@ public: { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); const std::string indexName = "a"; auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto iam = @@ -2447,7 +2447,7 @@ public: { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); const std::string indexName = "b"; auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto iam = @@ -2505,7 +2505,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -2551,7 +2551,7 @@ public: { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); InsertDeleteOptions options; options.logIfError = true; @@ -2708,7 +2708,7 @@ public: // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -2772,7 +2772,7 @@ public: void run() { // Create a new collection. lockDb(MODE_X); - Collection* coll; + const Collection* coll; { WriteUnitOfWork wunit(&_opCtx); ASSERT_OK(_db->dropCollection(&_opCtx, _nss)); @@ -2942,7 +2942,7 @@ public: // Create a new collection and insert non-multikey document. lockDb(MODE_X); - Collection* coll; + const Collection* coll; RecordId id1; BSONObj doc = BSON("_id" << 1 << "a" << 1); { @@ -2971,7 +2971,7 @@ public: // Set up a non-multikey index with multikey document. { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto iam = const_cast<IndexAccessMethod*>(indexCatalog->getEntry(descriptor)->accessMethod()); @@ -3164,7 +3164,7 @@ public: // Create a new collection and insert multikey document. lockDb(MODE_X); - Collection* coll; + const Collection* coll; RecordId id1; BSONObj doc1 = BSON("_id" << 1 << "a" << BSON_ARRAY(1 << 2) << "b" << 1); { @@ -3195,7 +3195,7 @@ public: { lockDb(MODE_X); - IndexCatalog* indexCatalog = coll->getIndexCatalog(); + const IndexCatalog* indexCatalog = coll->getIndexCatalog(); auto descriptor = indexCatalog->findIndexByName(&_opCtx, indexName); auto iam = const_cast<IndexAccessMethod*>(indexCatalog->getEntry(descriptor)->accessMethod()); diff --git a/src/mongo/dbtests/wildcard_multikey_persistence_test.cpp b/src/mongo/dbtests/wildcard_multikey_persistence_test.cpp index f611a733d6c..5e4a2d4c706 100644 --- a/src/mongo/dbtests/wildcard_multikey_persistence_test.cpp +++ b/src/mongo/dbtests/wildcard_multikey_persistence_test.cpp @@ -200,22 +200,29 @@ protected: auto indexSpec = (bob << "v" << kIndexVersion << "background" << background).obj(); Lock::DBLock dbLock(opCtx(), nss.db(), MODE_X); - AutoGetCollection autoColl(opCtx(), nss, MODE_X); - auto coll = autoColl.getCollection(); + AutoGetCollection coll(opCtx(), nss, MODE_X); MultiIndexBlock indexer; - auto abortOnExit = makeGuard( - [&] { indexer.abortIndexBuild(opCtx(), coll, MultiIndexBlock::kNoopOnCleanUpFn); }); + auto abortOnExit = makeGuard([&] { + indexer.abortIndexBuild( + opCtx(), coll.getWritableCollection(), MultiIndexBlock::kNoopOnCleanUpFn); + }); // Initialize the index builder and add all documents currently in the collection. - ASSERT_OK( - indexer.init(opCtx(), coll, indexSpec, MultiIndexBlock::kNoopOnInitFn).getStatus()); - ASSERT_OK(indexer.insertAllDocumentsInCollection(opCtx(), coll)); + ASSERT_OK(indexer + .init(opCtx(), + coll.getWritableCollection(), + indexSpec, + MultiIndexBlock::kNoopOnInitFn) + .getStatus()); + ASSERT_OK(indexer.insertAllDocumentsInCollection(opCtx(), coll.getCollection())); ASSERT_OK(indexer.checkConstraints(opCtx())); WriteUnitOfWork wunit(opCtx()); - ASSERT_OK(indexer.commit( - opCtx(), coll, MultiIndexBlock::kNoopOnCreateEachFn, MultiIndexBlock::kNoopOnCommitFn)); + ASSERT_OK(indexer.commit(opCtx(), + coll.getWritableCollection(), + MultiIndexBlock::kNoopOnCreateEachFn, + MultiIndexBlock::kNoopOnCommitFn)); abortOnExit.dismiss(); wunit.commit(); } |