From 3e76161bc537343aa585b305c068b1910578c07f Mon Sep 17 00:00:00 2001 From: Matt Broadstone Date: Fri, 14 Apr 2023 19:17:05 +0000 Subject: SERVER-75733 Return StringData in NSS::ns, DatabaseName::db --- src/mongo/client/dbclient_cursor.h | 2 +- src/mongo/client/dbclient_rs.cpp | 2 +- src/mongo/client/fetcher.cpp | 2 +- src/mongo/client/fetcher.h | 2 +- src/mongo/client/sasl_client_authenticate_impl.cpp | 4 +- src/mongo/db/auth/authorization_manager_impl.cpp | 4 +- src/mongo/db/auth/authorization_manager_test.cpp | 4 +- src/mongo/db/auth/authorization_session_impl.cpp | 3 +- src/mongo/db/auth/builtin_roles.tpl.cpp | 2 +- src/mongo/db/auth/sasl_mechanism_registry.h | 2 +- src/mongo/db/auth/sasl_mechanism_registry_test.cpp | 2 +- src/mongo/db/auth/user_cache_invalidator_job.cpp | 2 +- src/mongo/db/bulk_write_shard_test.cpp | 2 +- src/mongo/db/catalog/collection_catalog_test.cpp | 33 ++++++++----- src/mongo/db/catalog/drop_database_test.cpp | 2 +- src/mongo/db/catalog/rename_collection.cpp | 2 +- src/mongo/db/catalog_raii.cpp | 2 +- src/mongo/db/catalog_raii_test.cpp | 31 +++++++----- src/mongo/db/cloner.cpp | 2 +- src/mongo/db/commands.cpp | 6 +-- src/mongo/db/commands.h | 2 +- src/mongo/db/commands/authentication_commands.cpp | 7 ++- src/mongo/db/commands/dbcheck.cpp | 2 +- ...nal_rename_if_options_and_indexes_match_cmd.cpp | 2 +- src/mongo/db/commands/list_databases_common.h | 3 +- src/mongo/db/commands/mr_common.cpp | 2 +- src/mongo/db/commands/mr_common.h | 2 +- src/mongo/db/commands/mr_test.cpp | 2 +- src/mongo/db/commands/plan_cache_clear_command.cpp | 2 +- .../set_feature_compatibility_version_command.cpp | 4 +- src/mongo/db/commands/user_management_commands.cpp | 4 +- src/mongo/db/commands/validate_db_metadata_cmd.cpp | 6 +-- src/mongo/db/concurrency/lock_manager_defs.h | 3 +- src/mongo/db/curop.h | 4 +- src/mongo/db/database_name.h | 8 ++-- src/mongo/db/database_name_reserved.def.h | 2 + src/mongo/db/db_raii.cpp | 2 +- src/mongo/db/fle_crud.cpp | 2 +- src/mongo/db/namespace_string.h | 27 +++++------ src/mongo/db/op_observer/op_observer_impl_test.cpp | 8 ++-- .../shardsvr_process_interface.cpp | 2 +- src/mongo/db/query/canonical_query.h | 4 +- src/mongo/db/query/planner_access.cpp | 2 +- src/mongo/db/repl/cloner_test_fixture.cpp | 7 +-- src/mongo/db/repl/cloner_test_fixture.h | 2 +- src/mongo/db/repl/initial_syncer_test.cpp | 2 +- src/mongo/db/repl/oplog_applier_test.cpp | 3 +- src/mongo/db/repl/oplog_interface_remote.cpp | 2 +- src/mongo/db/repl/oplog_interface_remote.h | 2 +- ...replication_coordinator_external_state_impl.cpp | 2 +- src/mongo/db/repl/rollback_source_impl.cpp | 2 +- src/mongo/db/repl/rollback_source_impl.h | 2 +- src/mongo/db/repl/storage_interface_impl_test.cpp | 55 ++++++++++++---------- src/mongo/db/repl/tenant_collection_cloner.cpp | 2 +- src/mongo/db/repl/tenant_database_cloner.cpp | 2 +- src/mongo/db/repl/tenant_file_importer_service.cpp | 2 +- .../repl/tenant_migration_access_blocker_util.cpp | 2 +- .../tenant_migration_access_blocker_util_test.cpp | 27 +++++++---- src/mongo/db/s/analyze_shard_key_cmd_util.cpp | 6 ++- src/mongo/db/s/balancer/migration_test_fixture.cpp | 6 +-- .../db/s/config/configsvr_add_shard_command.cpp | 2 +- .../db/s/config/configsvr_remove_tags_command.cpp | 2 +- .../db/s/config/initial_split_policy_test.cpp | 4 +- ...talog_manager_assign_key_range_to_zone_test.cpp | 7 +-- .../sharding_catalog_manager_merge_chunks_test.cpp | 2 +- .../sharding_catalog_manager_zone_operations.cpp | 4 +- src/mongo/db/s/configure_query_analyzer_cmd.cpp | 2 +- src/mongo/db/s/drop_database_coordinator.cpp | 4 +- .../db/s/flush_database_cache_updates_command.cpp | 7 +-- .../global_index_cloning_service_test.cpp | 2 +- .../db/s/global_index/global_index_inserter.cpp | 2 +- .../s/global_index/global_index_inserter_test.cpp | 2 +- src/mongo/db/s/migration_destination_manager.cpp | 2 +- .../s/move_primary/move_primary_donor_service.cpp | 8 ++-- src/mongo/db/s/move_primary_coordinator.cpp | 4 +- src/mongo/db/s/move_primary_source_manager.cpp | 5 +- src/mongo/db/s/move_timing_helper.cpp | 2 +- src/mongo/db/s/move_timing_helper.h | 2 +- src/mongo/db/s/op_observer_sharding_impl.cpp | 6 +-- src/mongo/db/s/op_observer_sharding_test.cpp | 5 +- src/mongo/db/s/query_analysis_writer.cpp | 2 +- src/mongo/db/s/query_analysis_writer_test.cpp | 3 +- src/mongo/db/s/range_deletion_util.cpp | 11 +++-- src/mongo/db/s/rename_collection_coordinator.cpp | 4 +- src/mongo/db/s/reshard_collection_coordinator.cpp | 2 +- .../resharding_coordinator_commit_monitor.cpp | 2 +- .../resharding/resharding_coordinator_service.cpp | 21 +++++---- .../db/s/resharding/resharding_manual_cleanup.cpp | 2 +- .../db/s/sessions_collection_config_server.cpp | 2 +- .../db/s/shard_filtering_metadata_refresh.cpp | 14 +++--- .../sharding_catalog_client_aggregations_test.cpp | 24 ++++++---- src/mongo/db/s/sharding_ddl_coordinator.cpp | 3 +- .../db/s/sharding_ddl_coordinator_service.cpp | 2 +- src/mongo/db/s/sharding_ddl_util.cpp | 6 +-- src/mongo/db/s/sharding_ddl_util_test.cpp | 2 +- src/mongo/db/s/sharding_state_recovery.cpp | 3 +- src/mongo/db/s/sharding_util.cpp | 2 +- ...shardsvr_check_metadata_consistency_command.cpp | 2 +- src/mongo/db/s/shardsvr_drop_indexes_command.cpp | 2 +- src/mongo/db/service_entry_point_common.cpp | 4 +- src/mongo/db/shard_role.cpp | 3 +- src/mongo/db/shard_role_test.cpp | 10 ++-- src/mongo/db/stats/fill_locker_info_test.cpp | 6 +-- .../storage/wiredtiger/wiredtiger_record_store.cpp | 2 +- .../wiredtiger_record_store_test_harness.cpp | 2 +- src/mongo/db/ttl.cpp | 4 +- src/mongo/db/views/view_catalog_test.cpp | 14 +++--- src/mongo/db/views/view_definition_test.cpp | 3 +- src/mongo/dbtests/clienttests.cpp | 4 +- src/mongo/dbtests/dbtests.cpp | 2 +- src/mongo/dbtests/mock/mock_remote_db_server.cpp | 13 ++--- src/mongo/dbtests/mock/mock_remote_db_server.h | 2 +- .../dbtests/plan_executor_invalidation_test.cpp | 2 +- src/mongo/dbtests/query_stage_and.cpp | 4 +- src/mongo/dbtests/querytests.cpp | 10 ++-- src/mongo/dbtests/rollbacktests.cpp | 2 +- src/mongo/idl/idl_test.cpp | 2 +- .../s/catalog/sharding_catalog_client_impl.cpp | 2 +- src/mongo/s/client/shard_remote.cpp | 3 +- src/mongo/s/cluster_commands_helpers.cpp | 2 +- src/mongo/s/commands/cluster_count_cmd.h | 2 +- src/mongo/s/commands/cluster_distinct_cmd.cpp | 2 +- .../s/commands/cluster_drop_collection_cmd.cpp | 2 +- src/mongo/s/commands/cluster_move_primary_cmd.cpp | 2 +- .../s/commands/cluster_rename_collection_cmd.cpp | 2 +- .../commands/cluster_set_cluster_parameter_cmd.cpp | 2 +- ...uster_set_feature_compatibility_version_cmd.cpp | 2 +- .../s/commands/cluster_shard_collection_cmd.cpp | 2 +- .../cluster_transition_to_catalog_shard_cmd.cpp | 2 +- ...r_transition_to_dedicated_config_server_cmd.cpp | 2 +- .../commands/internal_transactions_test_command.h | 2 +- src/mongo/s/query_analysis_client.cpp | 2 +- src/mongo/util/assert_util_core.h | 9 ++-- 133 files changed, 356 insertions(+), 295 deletions(-) diff --git a/src/mongo/client/dbclient_cursor.h b/src/mongo/client/dbclient_cursor.h index c5cfd1484bb..9499e1ac51b 100644 --- a/src/mongo/client/dbclient_cursor.h +++ b/src/mongo/client/dbclient_cursor.h @@ -190,7 +190,7 @@ public: return _originalHost; } - std::string getns() const { + StringData getns() const { return _ns.ns(); } diff --git a/src/mongo/client/dbclient_rs.cpp b/src/mongo/client/dbclient_rs.cpp index 3257ee82712..368b1534ccb 100644 --- a/src/mongo/client/dbclient_rs.cpp +++ b/src/mongo/client/dbclient_rs.cpp @@ -502,7 +502,7 @@ std::unique_ptr DBClientReplicaSet::find(FindCommandRequest find const ReadPreferenceSetting& readPref, ExhaustMode exhaustMode) { invariant(findRequest.getNamespaceOrUUID().nss()); - const std::string nss = findRequest.getNamespaceOrUUID().nss()->ns(); + const std::string nss = findRequest.getNamespaceOrUUID().nss()->ns().toString(); if (_isSecondaryQuery(nss, findRequest.toBSON(BSONObj{}), readPref)) { LOGV2_DEBUG(5951202, 3, diff --git a/src/mongo/client/fetcher.cpp b/src/mongo/client/fetcher.cpp index 868ffb90a97..078ba89210a 100644 --- a/src/mongo/client/fetcher.cpp +++ b/src/mongo/client/fetcher.cpp @@ -167,7 +167,7 @@ Status parseCursorResponse(const BSONObj& obj, Fetcher::Fetcher(executor::TaskExecutor* executor, const HostAndPort& source, - const std::string& dbname, + StringData dbname, const BSONObj& findCmdObj, CallbackFn work, const BSONObj& metadata, diff --git a/src/mongo/client/fetcher.h b/src/mongo/client/fetcher.h index 90ba61b00fc..b81fbc222ed 100644 --- a/src/mongo/client/fetcher.h +++ b/src/mongo/client/fetcher.h @@ -130,7 +130,7 @@ public: */ Fetcher(executor::TaskExecutor* executor, const HostAndPort& source, - const std::string& dbname, + StringData dbname, const BSONObj& cmdObj, CallbackFn work, const BSONObj& metadata = ReadPreferenceSetting::secondaryPreferredMetadata(), diff --git a/src/mongo/client/sasl_client_authenticate_impl.cpp b/src/mongo/client/sasl_client_authenticate_impl.cpp index ffba7ba146d..1ceafc69d26 100644 --- a/src/mongo/client/sasl_client_authenticate_impl.cpp +++ b/src/mongo/client/sasl_client_authenticate_impl.cpp @@ -147,7 +147,7 @@ Status saslConfigureSession(SaslClientSession* session, status = bsonExtractStringField(saslParameters, saslCommandUserFieldName, &value); if (status.isOK()) { session->setParameter(SaslClientSession::parameterUser, value); - } else if ((targetDatabase != NamespaceString::kExternalDb) || + } else if ((targetDatabase != DatabaseName::kExternal.db()) || ((mechanism != auth::kMechanismMongoAWS) && (mechanism != auth::kMechanismMongoOIDC))) { return status; @@ -164,7 +164,7 @@ Status saslConfigureSession(SaslClientSession* session, if (status.isOK()) { session->setParameter(SaslClientSession::parameterPassword, value); } else if (!(status == ErrorCodes::NoSuchKey && - targetDatabase == NamespaceString::kExternalDb)) { + targetDatabase == DatabaseName::kExternal.db())) { // $external users do not have passwords, hence NoSuchKey is expected return status; } diff --git a/src/mongo/db/auth/authorization_manager_impl.cpp b/src/mongo/db/auth/authorization_manager_impl.cpp index 48d464814e6..aae5a36f297 100644 --- a/src/mongo/db/auth/authorization_manager_impl.cpp +++ b/src/mongo/db/auth/authorization_manager_impl.cpp @@ -411,7 +411,7 @@ StatusWith AuthorizationManagerImpl::acquireUser(OperationContext* o // X.509 will give us our roles for initial acquire, but we have to lose them during // reacquire (for now) so reparse those roles into the request if not already present. if ((request.roles == boost::none) && request.mechanismData.empty() && - (userName.getDB() == "$external"_sd)) { + (userName.getDB() == DatabaseName::kExternal.db())) { userRequest = getX509UserRequest(opCtx, std::move(userRequest)); } #endif @@ -530,7 +530,7 @@ Status AuthorizationManagerImpl::refreshExternalUsers(OperationContext* opCtx) { // First, get a snapshot of the UserHandles in the cache. auto cachedUsers = _userCache.peekLatestCachedIf([&](const UserRequest& userRequest, const User&) { - return userRequest.name.getDB() == "$external"_sd; + return userRequest.name.getDB() == DatabaseName::kExternal.db(); }); // Then, retrieve the corresponding Users from the backing store for users in the $external diff --git a/src/mongo/db/auth/authorization_manager_test.cpp b/src/mongo/db/auth/authorization_manager_test.cpp index 4a9f4db10ed..dcce21d5aea 100644 --- a/src/mongo/db/auth/authorization_manager_test.cpp +++ b/src/mongo/db/auth/authorization_manager_test.cpp @@ -349,7 +349,7 @@ TEST_F(AuthorizationManagerTest, testRefreshExternalV2User) { // Assert that all checked-out $external users are now marked invalid. for (const auto& checkedOutUser : checkedOutUsers) { - if (checkedOutUser->getName().getDB() == "$external"_sd) { + if (checkedOutUser->getName().getDB() == DatabaseName::kExternal.db()) { ASSERT(!checkedOutUser.isValid()); } else { ASSERT(checkedOutUser.isValid()); @@ -368,7 +368,7 @@ TEST_F(AuthorizationManagerTest, testRefreshExternalV2User) { ASSERT(user.isValid()); RoleNameIterator cachedUserRolesIt = user->getRoles(); - if (userDoc.getStringField(kDbFieldName) == "$external"_sd) { + if (userDoc.getStringField(kDbFieldName) == DatabaseName::kExternal.db()) { for (const auto& userDocRole : updatedRoles) { ASSERT_EQUALS(cachedUserRolesIt.next(), RoleName(userDocRole.getStringField(kRoleFieldName), diff --git a/src/mongo/db/auth/authorization_session_impl.cpp b/src/mongo/db/auth/authorization_session_impl.cpp index 82fb7078846..8e6e49300ea 100644 --- a/src/mongo/db/auth/authorization_session_impl.cpp +++ b/src/mongo/db/auth/authorization_session_impl.cpp @@ -732,7 +732,8 @@ void AuthorizationSessionImpl::_refreshUserInfoAsNeeded(OperationContext* opCtx) // backing LDAP host, it should be cleared from _authenticatedUser. This // guarantees that no operations can be performed until the LDAP host comes back up. // TODO SERVER-72678 avoid this edge case hack when rearchitecting user acquisition. - if (name.getDB() == "$external"_sd && currentUser->getUserRequest().mechanismData.empty()) { + if (name.getDB() == DatabaseName::kExternal.db() && + currentUser->getUserRequest().mechanismData.empty()) { clearUser(); LOGV2(5914804, "Removed external user from session cache of user information because of " diff --git a/src/mongo/db/auth/builtin_roles.tpl.cpp b/src/mongo/db/auth/builtin_roles.tpl.cpp index b698f34fce7..bf6445461ee 100644 --- a/src/mongo/db/auth/builtin_roles.tpl.cpp +++ b/src/mongo/db/auth/builtin_roles.tpl.cpp @@ -153,7 +153,7 @@ const stdx::unordered_set kAdminBuiltinRoles = { // Therefore, granting privileges on this database does not make sense. bool isValidDB(const DatabaseName& dbname) { return NamespaceString::validDBName(dbname, NamespaceString::DollarInDbNameBehavior::Allow) && - (dbname.db() != NamespaceString::kExternalDb); + (dbname.db() != DatabaseName::kExternal.db()); } } // namespace diff --git a/src/mongo/db/auth/sasl_mechanism_registry.h b/src/mongo/db/auth/sasl_mechanism_registry.h index 2112ad06e7d..b99138b6bd3 100644 --- a/src/mongo/db/auth/sasl_mechanism_registry.h +++ b/src/mongo/db/auth/sasl_mechanism_registry.h @@ -405,7 +405,7 @@ private: using MechList = std::vector>; MechList& _getMapRef(StringData dbName) { - return _getMapRef(dbName != "$external"_sd); + return _getMapRef(dbName != DatabaseName::kExternal.db()); } MechList& _getMapRef(bool internal) { diff --git a/src/mongo/db/auth/sasl_mechanism_registry_test.cpp b/src/mongo/db/auth/sasl_mechanism_registry_test.cpp index 11bdb673859..81d1e62c918 100644 --- a/src/mongo/db/auth/sasl_mechanism_registry_test.cpp +++ b/src/mongo/db/auth/sasl_mechanism_registry_test.cpp @@ -251,7 +251,7 @@ public: SASLServerMechanismRegistry registry; const UserName internalSajack = {"sajack"_sd, "test"_sd}; - const UserName externalSajack = {"sajack"_sd, "$external"_sd}; + const UserName externalSajack = {"sajack"_sd, DatabaseName::kExternal.db()}; }; TEST_F(MechanismRegistryTest, acquireInternalMechanism) { diff --git a/src/mongo/db/auth/user_cache_invalidator_job.cpp b/src/mongo/db/auth/user_cache_invalidator_job.cpp index fe8650325f5..d7c599f1fd9 100644 --- a/src/mongo/db/auth/user_cache_invalidator_job.cpp +++ b/src/mongo/db/auth/user_cache_invalidator_job.cpp @@ -197,7 +197,7 @@ void UserCacheInvalidator::run() { "users in cache", "error"_attr = refreshStatus); try { - _authzManager->invalidateUsersFromDB(opCtx.get(), "$external"_sd); + _authzManager->invalidateUsersFromDB(opCtx.get(), DatabaseName::kExternal); } catch (const DBException& e) { LOGV2_WARNING(5914805, "Error invalidating $external users from user cache", diff --git a/src/mongo/db/bulk_write_shard_test.cpp b/src/mongo/db/bulk_write_shard_test.cpp index 5cd470c43f2..77320fd28e9 100644 --- a/src/mongo/db/bulk_write_shard_test.cpp +++ b/src/mongo/db/bulk_write_shard_test.cpp @@ -117,7 +117,7 @@ void installDatabaseMetadata(OperationContext* opCtx, const DatabaseVersion& dbVersion) { AutoGetDb autoDb(opCtx, dbName, MODE_X); auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireExclusive(opCtx, dbName); - scopedDss->setDbInfo(opCtx, {dbName.db(), ShardId("this"), dbVersion}); + scopedDss->setDbInfo(opCtx, {dbName.db().toString(), ShardId("this"), dbVersion}); } void installUnshardedCollectionMetadata(OperationContext* opCtx, const NamespaceString& nss) { diff --git a/src/mongo/db/catalog/collection_catalog_test.cpp b/src/mongo/db/catalog/collection_catalog_test.cpp index 124af7ceb36..2fdb7571359 100644 --- a/src/mongo/db/catalog/collection_catalog_test.cpp +++ b/src/mongo/db/catalog/collection_catalog_test.cpp @@ -396,7 +396,8 @@ TEST_F(CollectionCatalogTest, OnDropCollection) { TEST_F(CollectionCatalogTest, RenameCollection) { auto uuid = UUID::gen(); - NamespaceString oldNss = NamespaceString::createNamespaceString_forTest(nss.db(), "oldcol"); + NamespaceString oldNss = + NamespaceString::createNamespaceString_forTest(DatabaseName{nss.db()}, "oldcol"); std::shared_ptr collShared = std::make_shared(uuid, oldNss); auto collection = collShared.get(); catalog.registerCollection(opCtx.get(), uuid, std::move(collShared), boost::none); @@ -1110,7 +1111,7 @@ private: } void _dropCollection(OperationContext* opCtx, const NamespaceString& nss, Timestamp timestamp) { - Lock::DBLock dbLk(opCtx, nss.db(), MODE_IX); + Lock::DBLock dbLk(opCtx, DatabaseName{nss.db()}, MODE_IX); Lock::CollectionLock collLk(opCtx, nss, MODE_X); CollectionWriter collection(opCtx, nss); @@ -1146,7 +1147,7 @@ private: const NamespaceString& from, const NamespaceString& to, Timestamp timestamp) { - Lock::DBLock dbLk(opCtx, from.db(), MODE_IX); + Lock::DBLock dbLk(opCtx, DatabaseName{from.db()}, MODE_IX); Lock::CollectionLock fromLk(opCtx, from, MODE_X); Lock::CollectionLock toLk(opCtx, to, MODE_X); @@ -2704,9 +2705,11 @@ TEST_F(CollectionCatalogTimestampTest, CatalogIdMappingInsert) { CollectionCatalog::get(opCtx.get()) ->establishConsistentCollection(opCtx.get(), nss, Timestamp(1, 17)); CollectionCatalog::get(opCtx.get()) - ->establishConsistentCollection(opCtx.get(), {nss.db(), firstUUID}, Timestamp(1, 17)); + ->establishConsistentCollection( + opCtx.get(), {DatabaseName{nss.db()}, firstUUID}, Timestamp(1, 17)); CollectionCatalog::get(opCtx.get()) - ->establishConsistentCollection(opCtx.get(), {nss.db(), secondUUID}, Timestamp(1, 17)); + ->establishConsistentCollection( + opCtx.get(), {DatabaseName{nss.db()}, secondUUID}, Timestamp(1, 17)); // Lookups before the inserted timestamp is still unknown ASSERT_EQ(lookupCatalogId(nss, firstUUID, Timestamp(1, 11)).result, @@ -2737,9 +2740,11 @@ TEST_F(CollectionCatalogTimestampTest, CatalogIdMappingInsert) { CollectionCatalog::get(opCtx.get()) ->establishConsistentCollection(opCtx.get(), nss, Timestamp(1, 12)); CollectionCatalog::get(opCtx.get()) - ->establishConsistentCollection(opCtx.get(), {nss.db(), firstUUID}, Timestamp(1, 12)); + ->establishConsistentCollection( + opCtx.get(), {DatabaseName{nss.db()}, firstUUID}, Timestamp(1, 12)); CollectionCatalog::get(opCtx.get()) - ->establishConsistentCollection(opCtx.get(), {nss.db(), secondUUID}, Timestamp(1, 12)); + ->establishConsistentCollection( + opCtx.get(), {DatabaseName{nss.db()}, secondUUID}, Timestamp(1, 12)); // We should now have extended the range from Timestamp(1, 17) to Timestamp(1, 12) ASSERT_EQ(lookupCatalogId(nss, firstUUID, Timestamp(1, 12)).result, @@ -2769,9 +2774,11 @@ TEST_F(CollectionCatalogTimestampTest, CatalogIdMappingInsert) { CollectionCatalog::get(opCtx.get()) ->establishConsistentCollection(opCtx.get(), nss, Timestamp(1, 25)); CollectionCatalog::get(opCtx.get()) - ->establishConsistentCollection(opCtx.get(), {nss.db(), firstUUID}, Timestamp(1, 25)); + ->establishConsistentCollection( + opCtx.get(), {DatabaseName{nss.db()}, firstUUID}, Timestamp(1, 25)); CollectionCatalog::get(opCtx.get()) - ->establishConsistentCollection(opCtx.get(), {nss.db(), secondUUID}, Timestamp(1, 25)); + ->establishConsistentCollection( + opCtx.get(), {DatabaseName{nss.db()}, secondUUID}, Timestamp(1, 25)); // Check the entries, most didn't change ASSERT_EQ(lookupCatalogId(nss, firstUUID, Timestamp(1, 17)).result, @@ -2805,9 +2812,11 @@ TEST_F(CollectionCatalogTimestampTest, CatalogIdMappingInsert) { CollectionCatalog::get(opCtx.get()) ->establishConsistentCollection(opCtx.get(), nss, Timestamp(1, 26)); CollectionCatalog::get(opCtx.get()) - ->establishConsistentCollection(opCtx.get(), {nss.db(), firstUUID}, Timestamp(1, 26)); + ->establishConsistentCollection( + opCtx.get(), {DatabaseName{nss.db()}, firstUUID}, Timestamp(1, 26)); CollectionCatalog::get(opCtx.get()) - ->establishConsistentCollection(opCtx.get(), {nss.db(), secondUUID}, Timestamp(1, 26)); + ->establishConsistentCollection( + opCtx.get(), {DatabaseName{nss.db()}, secondUUID}, Timestamp(1, 26)); // We should not have re-written the existing entry at Timestamp(1, 26) ASSERT_EQ(lookupCatalogId(nss, firstUUID, Timestamp(1, 17)).result, @@ -3934,7 +3943,7 @@ TEST_F(CollectionCatalogTimestampTest, ResolveNamespaceStringOrUUIDAtLatest) { const NamespaceString nss = NamespaceString::createNamespaceString_forTest("a.b"); const Timestamp createCollectionTs = Timestamp(10, 10); const UUID uuid = createCollection(opCtx.get(), nss, createCollectionTs); - const NamespaceStringOrUUID nssOrUUID = NamespaceStringOrUUID(nss.db(), uuid); + const NamespaceStringOrUUID nssOrUUID = NamespaceStringOrUUID(DatabaseName{nss.db()}, uuid); NamespaceString resolvedNss = CollectionCatalog::get(opCtx.get())->resolveNamespaceStringOrUUID(opCtx.get(), nssOrUUID); diff --git a/src/mongo/db/catalog/drop_database_test.cpp b/src/mongo/db/catalog/drop_database_test.cpp index 9f9ea38f8f6..fd29c8b9f07 100644 --- a/src/mongo/db/catalog/drop_database_test.cpp +++ b/src/mongo/db/catalog/drop_database_test.cpp @@ -198,7 +198,7 @@ void _createCollection(OperationContext* opCtx, const NamespaceString& nss) { * Removes database from catalog, bypassing dropDatabase(). */ void _removeDatabaseFromCatalog(OperationContext* opCtx, StringData dbName) { - AutoGetDb autoDB(opCtx, dbName, MODE_X); + AutoGetDb autoDB(opCtx, DatabaseName{dbName}, MODE_X); auto db = autoDB.getDb(); // dropDatabase can call awaitReplication more than once, so do not attempt to drop the database // twice. diff --git a/src/mongo/db/catalog/rename_collection.cpp b/src/mongo/db/catalog/rename_collection.cpp index e399d47b76a..21939a4a1d7 100644 --- a/src/mongo/db/catalog/rename_collection.cpp +++ b/src/mongo/db/catalog/rename_collection.cpp @@ -482,7 +482,7 @@ Status renameCollectionAcrossDatabases(OperationContext* opCtx, targetDBLock.emplace(opCtx, target.dbName(), MODE_X); } - DatabaseShardingState::assertMatchingDbVersion(opCtx, source.db()); + DatabaseShardingState::assertMatchingDbVersion(opCtx, DatabaseName{source.db()}); DisableDocumentValidation validationDisabler(opCtx); diff --git a/src/mongo/db/catalog_raii.cpp b/src/mongo/db/catalog_raii.cpp index 1773269fd77..704c5480de2 100644 --- a/src/mongo/db/catalog_raii.cpp +++ b/src/mongo/db/catalog_raii.cpp @@ -483,7 +483,7 @@ AutoGetCollectionLockFree::AutoGetCollectionLockFree(OperationContext* opCtx, // Check that the sharding database version matches our read. // Note: this must always be checked, regardless of whether the collection exists, so that the // dbVersion of this node or the caller gets updated quickly in case either is stale. - DatabaseShardingState::assertMatchingDbVersion(opCtx, _resolvedNss.db()); + DatabaseShardingState::assertMatchingDbVersion(opCtx, DatabaseName{_resolvedNss.db()}); checkCollectionUUIDMismatch(opCtx, _resolvedNss, _collectionPtr, options._expectedUUID); diff --git a/src/mongo/db/catalog_raii_test.cpp b/src/mongo/db/catalog_raii_test.cpp index 7ed2fc9f3b5..e273eb65639 100644 --- a/src/mongo/db/catalog_raii_test.cpp +++ b/src/mongo/db/catalog_raii_test.cpp @@ -240,8 +240,8 @@ TEST_F(CatalogRAIITestFixture, AutoGetCollectionSecondaryNamespacesSingleDb) { ASSERT(opCtx1->lockState()->isRSTLLocked()); ASSERT(opCtx1->lockState()->isReadLocked()); // Global lock check ASSERT(opCtx1->lockState()->isDbLockedForMode(nss.dbName(), MODE_IS)); - ASSERT(opCtx1->lockState()->isDbLockedForMode(kSecondaryNss1.db(), MODE_IS)); - ASSERT(opCtx1->lockState()->isDbLockedForMode(kSecondaryNss2.db(), MODE_IS)); + ASSERT(opCtx1->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNss1.db()}, MODE_IS)); + ASSERT(opCtx1->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNss2.db()}, MODE_IS)); ASSERT(opCtx1->lockState()->isCollectionLockedForMode(nss, MODE_IS)); ASSERT(opCtx1->lockState()->isCollectionLockedForMode(kSecondaryNss1, MODE_IS)); ASSERT(opCtx1->lockState()->isCollectionLockedForMode(kSecondaryNss2, MODE_IS)); @@ -249,8 +249,10 @@ TEST_F(CatalogRAIITestFixture, AutoGetCollectionSecondaryNamespacesSingleDb) { ASSERT(!opCtx1->lockState()->isRSTLExclusive()); ASSERT(!opCtx1->lockState()->isGlobalLockedRecursively()); ASSERT(!opCtx1->lockState()->isWriteLocked()); - ASSERT(!opCtx1->lockState()->isDbLockedForMode(kSecondaryNssOtherDb1.db(), MODE_IS)); - ASSERT(!opCtx1->lockState()->isDbLockedForMode(kSecondaryNssOtherDb2.db(), MODE_IS)); + ASSERT( + !opCtx1->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNssOtherDb1.db()}, MODE_IS)); + ASSERT( + !opCtx1->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNssOtherDb2.db()}, MODE_IS)); ASSERT(!opCtx1->lockState()->isCollectionLockedForMode(kSecondaryNssOtherDb1, MODE_IS)); ASSERT(!opCtx1->lockState()->isCollectionLockedForMode(kSecondaryNssOtherDb2, MODE_IS)); @@ -276,16 +278,18 @@ TEST_F(CatalogRAIITestFixture, AutoGetCollectionMultiNamespacesMODEIX) { ASSERT(opCtx1->lockState()->isRSTLLocked()); ASSERT(opCtx1->lockState()->isWriteLocked()); // Global lock check ASSERT(opCtx1->lockState()->isDbLockedForMode(nss.dbName(), MODE_IX)); - ASSERT(opCtx1->lockState()->isDbLockedForMode(kSecondaryNss1.db(), MODE_IX)); - ASSERT(opCtx1->lockState()->isDbLockedForMode(kSecondaryNss2.db(), MODE_IX)); + ASSERT(opCtx1->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNss1.db()}, MODE_IX)); + ASSERT(opCtx1->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNss2.db()}, MODE_IX)); ASSERT(opCtx1->lockState()->isCollectionLockedForMode(nss, MODE_IX)); ASSERT(opCtx1->lockState()->isCollectionLockedForMode(kSecondaryNss1, MODE_IX)); ASSERT(opCtx1->lockState()->isCollectionLockedForMode(kSecondaryNss2, MODE_IX)); ASSERT(!opCtx1->lockState()->isRSTLExclusive()); ASSERT(!opCtx1->lockState()->isGlobalLockedRecursively()); - ASSERT(!opCtx1->lockState()->isDbLockedForMode(kSecondaryNssOtherDb1.db(), MODE_IX)); - ASSERT(!opCtx1->lockState()->isDbLockedForMode(kSecondaryNssOtherDb2.db(), MODE_IX)); + ASSERT( + !opCtx1->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNssOtherDb1.db()}, MODE_IX)); + ASSERT( + !opCtx1->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNssOtherDb2.db()}, MODE_IX)); ASSERT(!opCtx1->lockState()->isCollectionLockedForMode(kSecondaryNssOtherDb1, MODE_IX)); ASSERT(!opCtx1->lockState()->isCollectionLockedForMode(kSecondaryNssOtherDb2, MODE_IX)); @@ -303,11 +307,11 @@ TEST_F(CatalogRAIITestFixture, AutoGetDbSecondaryNamespacesSingleDb) { ASSERT(opCtx1->lockState()->isRSTLLocked()); ASSERT(opCtx1->lockState()->isReadLocked()); // Global lock check ASSERT(opCtx1->lockState()->isDbLockedForMode(nss.dbName(), MODE_IS)); - ASSERT(opCtx1->lockState()->isDbLockedForMode(kSecondaryNss1.db(), MODE_IS)); - ASSERT(opCtx1->lockState()->isDbLockedForMode(kSecondaryNss2.db(), MODE_IS)); + ASSERT(opCtx1->lockState()->isDbLockedForMode(kSecondaryNss1.dbName(), MODE_IS)); + ASSERT(opCtx1->lockState()->isDbLockedForMode(kSecondaryNss2.dbName(), MODE_IS)); - ASSERT(!opCtx1->lockState()->isDbLockedForMode(kSecondaryNssOtherDb1.db(), MODE_IS)); - ASSERT(!opCtx1->lockState()->isDbLockedForMode(kSecondaryNssOtherDb2.db(), MODE_IS)); + ASSERT(!opCtx1->lockState()->isDbLockedForMode(kSecondaryNssOtherDb1.dbName(), MODE_IS)); + ASSERT(!opCtx1->lockState()->isDbLockedForMode(kSecondaryNssOtherDb2.dbName(), MODE_IS)); ASSERT(!opCtx1->lockState()->isRSTLExclusive()); ASSERT(!opCtx1->lockState()->isGlobalLockedRecursively()); ASSERT(!opCtx1->lockState()->isWriteLocked()); @@ -321,7 +325,8 @@ TEST_F(CatalogRAIITestFixture, AutoGetCollectionMultiNssCollLockDeadline) { // Take a MODE_X collection lock on kSecondaryNss1. boost::optional autoGetCollWithXLock; autoGetCollWithXLock.emplace(client1.second.get(), kSecondaryNss1, MODE_X); - ASSERT(client1.second->lockState()->isDbLockedForMode(kSecondaryNss1.db(), MODE_IX)); + ASSERT( + client1.second->lockState()->isDbLockedForMode(DatabaseName{kSecondaryNss1.db()}, MODE_IX)); ASSERT(client1.second->lockState()->isCollectionLockedForMode(kSecondaryNss1, MODE_X)); // Now trying to take a MODE_IS lock on kSecondaryNss1 as a secondary collection should fail. diff --git a/src/mongo/db/cloner.cpp b/src/mongo/db/cloner.cpp index 682208b774e..1f9f7f0f255 100644 --- a/src/mongo/db/cloner.cpp +++ b/src/mongo/db/cloner.cpp @@ -597,7 +597,7 @@ Status Cloner::copyDb(OperationContext* opCtx, const NamespaceString nss(dBName, params.collectionName); - clonedColls->insert(nss.ns()); + clonedColls->insert(nss.ns().toString()); LOGV2_DEBUG(20421, 1, "\t\t cloning", logAttrs(nss), "host"_attr = masterHost); diff --git a/src/mongo/db/commands.cpp b/src/mongo/db/commands.cpp index 868c37da94f..1cc63cf1336 100644 --- a/src/mongo/db/commands.cpp +++ b/src/mongo/db/commands.cpp @@ -280,7 +280,7 @@ std::string CommandHelpers::parseNsFullyQualified(const BSONObj& cmdObj) { uassert(ErrorCodes::InvalidNamespace, str::stream() << "Invalid namespace specified '" << nss.ns() << "'", nss.isValid()); - return nss.ns(); + return nss.ns().toString(); } NamespaceString CommandHelpers::parseNsCollectionRequired(const DatabaseName& dbName, @@ -321,7 +321,7 @@ NamespaceStringOrUUID CommandHelpers::parseNsOrUUID(const DatabaseName& dbName, } std::string CommandHelpers::parseNsFromCommand(StringData dbname, const BSONObj& cmdObj) { - return parseNsFromCommand({boost::none, dbname}, cmdObj).ns(); + return parseNsFromCommand({boost::none, dbname}, cmdObj).ns().toString(); } NamespaceString CommandHelpers::parseNsFromCommand(const DatabaseName& dbName, @@ -333,7 +333,7 @@ NamespaceString CommandHelpers::parseNsFromCommand(const DatabaseName& dbName, cmdObj.firstElement().valueStringData()); } -ResourcePattern CommandHelpers::resourcePatternForNamespace(const std::string& ns) { +ResourcePattern CommandHelpers::resourcePatternForNamespace(StringData ns) { if (!NamespaceString::validCollectionComponent(ns)) { return ResourcePattern::forDatabaseName(ns); } diff --git a/src/mongo/db/commands.h b/src/mongo/db/commands.h index d06b9a12805..e88f43b8d2b 100644 --- a/src/mongo/db/commands.h +++ b/src/mongo/db/commands.h @@ -165,7 +165,7 @@ struct CommandHelpers { * pattern or a database resource pattern, depending on whether parseNs returns a fully qualifed * collection name or just a database name. */ - static ResourcePattern resourcePatternForNamespace(const std::string& ns); + static ResourcePattern resourcePatternForNamespace(StringData ns); static Command* findCommand(StringData name); diff --git a/src/mongo/db/commands/authentication_commands.cpp b/src/mongo/db/commands/authentication_commands.cpp index 97419827dde..f1c02c967a1 100644 --- a/src/mongo/db/commands/authentication_commands.cpp +++ b/src/mongo/db/commands/authentication_commands.cpp @@ -59,7 +59,6 @@ namespace mongo { namespace { -constexpr auto kExternalDB = "$external"_sd; constexpr auto kDBFieldName = "db"_sd; /** @@ -122,7 +121,7 @@ public: as->logoutDatabase( opCtx->getClient(), dbname.toStringWithTenantId(), "Logging out on user request"); - if (getTestCommandsEnabled() && (dbname == kAdminDB)) { + if (getTestCommandsEnabled() && (dbname.db() == kAdminDB)) { // Allows logging out as the internal user against the admin database, however // this actually logs out of the local database as well. This is to // support the auth passthrough test framework on mongos (since you can't use the @@ -213,7 +212,7 @@ void _authenticateX509(OperationContext* opCtx, AuthenticationSession* session) uassert(ErrorCodes::ProtocolError, "X.509 authentication must always use the $external database.", - userName.getDB() == kExternalDB); + userName.getDB() == DatabaseName::kExternal.db()); auto isInternalClient = [&]() -> bool { return opCtx->getClient()->session()->getTags() & transport::Session::kInternalClient; @@ -396,7 +395,7 @@ void doSpeculativeAuthenticate(OperationContext* opCtx, if (!hasDBField) { // No "db" field was provided, so default to "$external" - cmd.append(AuthenticateCommand::kDbNameFieldName, kExternalDB); + cmd.append(AuthenticateCommand::kDbNameFieldName, DatabaseName::kExternal.db()); } auto authCmdObj = diff --git a/src/mongo/db/commands/dbcheck.cpp b/src/mongo/db/commands/dbcheck.cpp index 5e1e700c894..94962d9f9a8 100644 --- a/src/mongo/db/commands/dbcheck.cpp +++ b/src/mongo/db/commands/dbcheck.cpp @@ -543,7 +543,7 @@ private: collection = catalog->establishConsistentCollection( opCtx, - {info.nss.db(), info.uuid}, + {DatabaseName{info.nss.db()}, info.uuid}, opCtx->recoveryUnit()->getPointInTimeReadTimestamp(opCtx)); } else { autoColl.emplace(opCtx, info.nss, MODE_IS); diff --git a/src/mongo/db/commands/internal_rename_if_options_and_indexes_match_cmd.cpp b/src/mongo/db/commands/internal_rename_if_options_and_indexes_match_cmd.cpp index 4a12c44304f..c171aae513b 100644 --- a/src/mongo/db/commands/internal_rename_if_options_and_indexes_match_cmd.cpp +++ b/src/mongo/db/commands/internal_rename_if_options_and_indexes_match_cmd.cpp @@ -78,7 +78,7 @@ public: } // Check if the receiving shard is still the primary for the database - DatabaseShardingState::assertIsPrimaryShardForDb(opCtx, fromNss.db()); + DatabaseShardingState::assertIsPrimaryShardForDb(opCtx, DatabaseName{fromNss.db()}); // Acquiring the local part of the distributed locks for involved namespaces allows: // - Serialize with sharded DDLs, ensuring no concurrent modifications of the diff --git a/src/mongo/db/commands/list_databases_common.h b/src/mongo/db/commands/list_databases_common.h index 2143131f882..942f1e76aff 100644 --- a/src/mongo/db/commands/list_databases_common.h +++ b/src/mongo/db/commands/list_databases_common.h @@ -99,7 +99,8 @@ int64_t setReplyItems(OperationContext* opCtx, } // If setTenantId is true, always return the dbName without the tenantId - ReplyItemType item(setTenantId ? dbName.db() : DatabaseNameUtil::serialize(dbName)); + ReplyItemType item(setTenantId ? dbName.db().toString() + : DatabaseNameUtil::serialize(dbName)); if (setTenantId) { initializeItemWithTenantId(item, dbName); } diff --git a/src/mongo/db/commands/mr_common.cpp b/src/mongo/db/commands/mr_common.cpp index 51d7e7191d4..0806741d992 100644 --- a/src/mongo/db/commands/mr_common.cpp +++ b/src/mongo/db/commands/mr_common.cpp @@ -269,7 +269,7 @@ auto translateOut(boost::intrusive_ptr expCtx, } // namespace -OutputOptions parseOutputOptions(const std::string& dbname, const BSONObj& cmdObj) { +OutputOptions parseOutputOptions(StringData dbname, const BSONObj& cmdObj) { OutputOptions outputOptions; outputOptions.outNonAtomic = true; diff --git a/src/mongo/db/commands/mr_common.h b/src/mongo/db/commands/mr_common.h index 965553e9ca8..0cb693453bb 100644 --- a/src/mongo/db/commands/mr_common.h +++ b/src/mongo/db/commands/mr_common.h @@ -49,7 +49,7 @@ struct OutputOptions { OutputType outType; }; -OutputOptions parseOutputOptions(const std::string& dbname, const BSONObj& cmdObj); +OutputOptions parseOutputOptions(StringData dbname, const BSONObj& cmdObj); Status checkAuthForMapReduce(const BasicCommand* command, OperationContext* opCtx, diff --git a/src/mongo/db/commands/mr_test.cpp b/src/mongo/db/commands/mr_test.cpp index 38cc3f73f81..6813016e3f7 100644 --- a/src/mongo/db/commands/mr_test.cpp +++ b/src/mongo/db/commands/mr_test.cpp @@ -112,7 +112,7 @@ void _testConfigParseOutputOptions(const std::string& dbname, _compareOutputOptionField(dbname, cmdObjStr, "finalNamespace", - outputOptions.finalNamespace.ns(), + outputOptions.finalNamespace.ns().toString(), expectedFinalNamespace); _compareOutputOptionField( dbname, cmdObjStr, "outNonAtomic", outputOptions.outNonAtomic, expectedOutNonAtomic); diff --git a/src/mongo/db/commands/plan_cache_clear_command.cpp b/src/mongo/db/commands/plan_cache_clear_command.cpp index 7fa1bd499a2..b95ee31751c 100644 --- a/src/mongo/db/commands/plan_cache_clear_command.cpp +++ b/src/mongo/db/commands/plan_cache_clear_command.cpp @@ -67,7 +67,7 @@ PlanCache* getPlanCache(OperationContext* opCtx, const CollectionPtr& collection Status clear(OperationContext* opCtx, const CollectionPtr& collection, PlanCache* planCache, - const std::string& ns, + StringData ns, const BSONObj& cmdObj) { invariant(planCache); diff --git a/src/mongo/db/commands/set_feature_compatibility_version_command.cpp b/src/mongo/db/commands/set_feature_compatibility_version_command.cpp index f29ead477f5..645fd108bdb 100644 --- a/src/mongo/db/commands/set_feature_compatibility_version_command.cpp +++ b/src/mongo/db/commands/set_feature_compatibility_version_command.cpp @@ -163,7 +163,7 @@ void abortAllReshardCollection(OperationContext* opCtx) { std::vector nsWithReshardColl; store.forEach(opCtx, {}, [&](const ReshardingCoordinatorDocument& doc) { - nsWithReshardColl.push_back(doc.getSourceNss().ns()); + nsWithReshardColl.push_back(doc.getSourceNss().ns().toString()); return true; }); @@ -843,7 +843,7 @@ private: ConfigsvrSetClusterParameter configsvrSetClusterParameter( BSON("shardedClusterCardinalityForDirectConns" << BSON("hasTwoOrMoreShards" << expectedValue))); - configsvrSetClusterParameter.setDbName(DatabaseName(boost::none, "admin")); + configsvrSetClusterParameter.setDbName(DatabaseName::kAdmin); const auto shardRegistry = Grid::get(opCtx)->shardRegistry(); const auto cmdResponse = diff --git a/src/mongo/db/commands/user_management_commands.cpp b/src/mongo/db/commands/user_management_commands.cpp index a3c9fdb8bb3..e6b6a3cdae0 100644 --- a/src/mongo/db/commands/user_management_commands.cpp +++ b/src/mongo/db/commands/user_management_commands.cpp @@ -1013,7 +1013,7 @@ void CmdUMCTyped::Invocation::typedRun(OperationContext* opCt cmd.getCommandParameter().find('\0') == std::string::npos); UserName userName(cmd.getCommandParameter(), dbname); - const bool isExternal = dbname.db() == NamespaceString::kExternalDb; + const bool isExternal = dbname.db() == DatabaseName::kExternal.db(); uassert(ErrorCodes::BadValue, "Must provide a 'pwd' field for all user documents, except those" " with '$external' as the user's source db", @@ -1505,7 +1505,7 @@ void CmdUMCTyped::Invocation::typedRun(OperationContext* opCt uassert(ErrorCodes::BadValue, "Cannot create roles in the $external database", - dbname.db() != NamespaceString::kExternalDb); + dbname.db() != DatabaseName::kExternal.db()); uassert(ErrorCodes::BadValue, "Cannot create roles with the same name as a built-in role", diff --git a/src/mongo/db/commands/validate_db_metadata_cmd.cpp b/src/mongo/db/commands/validate_db_metadata_cmd.cpp index ea4a72feb8d..db2f3fa66ef 100644 --- a/src/mongo/db/commands/validate_db_metadata_cmd.cpp +++ b/src/mongo/db/commands/validate_db_metadata_cmd.cpp @@ -167,7 +167,7 @@ public: bool _validateView(OperationContext* opCtx, const ViewDefinition& view) { auto pipelineStatus = view_catalog_helpers::validatePipeline(opCtx, view); if (!pipelineStatus.isOK()) { - ErrorReplyElement error(view.name().ns(), + ErrorReplyElement error(view.name().ns().toString(), ErrorCodes::APIStrictError, ErrorCodes::errorString(ErrorCodes::APIStrictError), pipelineStatus.getStatus().reason()); @@ -204,7 +204,7 @@ public: } const auto status = collection->checkValidatorAPIVersionCompatability(opCtx); if (!status.isOK()) { - ErrorReplyElement error(coll.nss()->ns(), + ErrorReplyElement error(coll.nss()->ns().toString(), ErrorCodes::APIStrictError, ErrorCodes::errorString(ErrorCodes::APIStrictError), status.reason()); @@ -227,7 +227,7 @@ public: const IndexDescriptor* desc = ii->next()->descriptor(); if (apiStrict && apiVersion == "1" && !index_key_validate::isIndexAllowedInAPIVersion1(*desc)) { - ErrorReplyElement error(coll.nss()->ns(), + ErrorReplyElement error(coll.nss()->ns().toString(), ErrorCodes::APIStrictError, ErrorCodes::errorString(ErrorCodes::APIStrictError), str::stream() diff --git a/src/mongo/db/concurrency/lock_manager_defs.h b/src/mongo/db/concurrency/lock_manager_defs.h index 6fbf8968552..23376734fe2 100644 --- a/src/mongo/db/concurrency/lock_manager_defs.h +++ b/src/mongo/db/concurrency/lock_manager_defs.h @@ -246,8 +246,7 @@ public: : _fullHash(fullHash(type, hashStringData(dbName.toStringWithTenantId()))) { verifyNoResourceMutex(type); } - ResourceId(ResourceType type, const std::string& str) - : _fullHash(fullHash(type, hashStringData(str))) { + ResourceId(ResourceType type, StringData str) : _fullHash(fullHash(type, hashStringData(str))) { // Resources of type database, collection, or tenant must never be passed as a raw string. invariant(type != RESOURCE_DATABASE && type != RESOURCE_COLLECTION && type != RESOURCE_TENANT); diff --git a/src/mongo/db/curop.h b/src/mongo/db/curop.h index 1c480498d7c..c915ffb2fcd 100644 --- a/src/mongo/db/curop.h +++ b/src/mongo/db/curop.h @@ -577,7 +577,9 @@ public: if (_dbprofile <= 0) return false; - if (CollectionCatalog::get(opCtx())->getDatabaseProfileSettings(getNSS().db()).filter) + if (CollectionCatalog::get(opCtx()) + ->getDatabaseProfileSettings(DatabaseName{getNSS().db()}) + .filter) return true; return elapsedTimeExcludingPauses() >= Milliseconds{serverGlobalParams.slowMS.load()}; diff --git a/src/mongo/db/database_name.h b/src/mongo/db/database_name.h index f68876bd030..63649f5c50d 100644 --- a/src/mongo/db/database_name.h +++ b/src/mongo/db/database_name.h @@ -131,19 +131,19 @@ public: * Prefer to use the constructor above. * TODO SERVER-65456 Remove this constructor. */ - DatabaseName(StringData dbName, boost::optional tenantId = boost::none) + explicit DatabaseName(StringData dbName, boost::optional tenantId = boost::none) : DatabaseName(std::move(tenantId), dbName) {} const boost::optional& tenantId() const { return _tenantId; } - const std::string& db() const { + StringData db() const { return _dbString; } - const std::string& toString() const { - return db(); + std::string toString() const { + return db().toString(); } std::string toStringWithTenantId() const { diff --git a/src/mongo/db/database_name_reserved.def.h b/src/mongo/db/database_name_reserved.def.h index 062fdd4317e..38b0cf17684 100644 --- a/src/mongo/db/database_name_reserved.def.h +++ b/src/mongo/db/database_name_reserved.def.h @@ -46,4 +46,6 @@ DBNAME_CONSTANT(kConfig, "config"_sd) DBNAME_CONSTANT(kSystem, "system"_sd) +DBNAME_CONSTANT(kExternal, "$external"_sd) + DBNAME_CONSTANT(kEmpty, ""_sd) diff --git a/src/mongo/db/db_raii.cpp b/src/mongo/db/db_raii.cpp index 64b9dbe68a0..3e9dde0821b 100644 --- a/src/mongo/db/db_raii.cpp +++ b/src/mongo/db/db_raii.cpp @@ -1304,7 +1304,7 @@ AutoGetCollectionForReadLockFreePITCatalog::AutoGetCollectionForReadLockFreePITC invariant(supportsLockFreeRead(opCtx) && (!opCtx->recoveryUnit()->isActive() || _isLockFreeReadSubOperation)); - DatabaseShardingState::assertMatchingDbVersion(opCtx, nsOrUUID.db()); + DatabaseShardingState::assertMatchingDbVersion(opCtx, DatabaseName{nsOrUUID.db()}); auto readConcernArgs = repl::ReadConcernArgs::get(opCtx); if (_isLockFreeReadSubOperation) { diff --git a/src/mongo/db/fle_crud.cpp b/src/mongo/db/fle_crud.cpp index 2cf9e1a5b6f..ed7e1be568c 100644 --- a/src/mongo/db/fle_crud.cpp +++ b/src/mongo/db/fle_crud.cpp @@ -1507,7 +1507,7 @@ std::vector> FLEQueryInterfaceImpl::getTags( getCountsCmd.setTokens(toTagSets(tokensSets)); getCountsCmd.setQueryType(queryTypeTranslation(type)); - auto response = _txnClient.runCommandSync(nss.db(), getCountsCmd.toBSON({})); + auto response = _txnClient.runCommandSync(DatabaseName{nss.db()}, getCountsCmd.toBSON({})); auto status = getStatusFromWriteCommandReply(response); uassertStatusOK(status); diff --git a/src/mongo/db/namespace_string.h b/src/mongo/db/namespace_string.h index e53a46b5e12..6c59a451422 100644 --- a/src/mongo/db/namespace_string.h +++ b/src/mongo/db/namespace_string.h @@ -139,9 +139,6 @@ public: // Reserved system namespaces - // The $external database used by X.509, LDAP, etc... - static constexpr StringData kExternalDb = "$external"_sd; - // Name for the system views collection static constexpr StringData kSystemDotViewsCollectionName = "system.views"_sd; @@ -416,19 +413,20 @@ public: : StringData(_ns.c_str() + _dotIndex + 1, _ns.size() - 1 - _dotIndex); } - const std::string& ns() const { - return _ns; + StringData ns() const { + return StringData{_ns}; } - const std::string& toString() const { - return ns(); + std::string toString() const { + return ns().toString(); } std::string toStringWithTenantId() const { - if (auto tenantId = _dbName.tenantId()) + if (auto tenantId = _dbName.tenantId()) { return str::stream() << *tenantId << '_' << ns(); + } - return ns(); + return ns().toString(); } /** @@ -443,10 +441,11 @@ public: * It is called anytime a NamespaceString is logged by logAttrs or otherwise. */ friend std::string toStringForLogging(const NamespaceString& nss) { - if (auto tenantId = nss.tenantId()) - return str::stream() << *tenantId << '_' << nss.ns(); + if (auto tenantId = nss.tenantId()) { + return str::stream() << *tenantId << '_' << nss.ns().toString(); + } - return nss.ns(); + return nss.ns().toString(); } size_t size() const { @@ -848,7 +847,7 @@ private: std::tuple&, const std::string&> _lens() const { - return std::tie(tenantId(), ns()); + return std::tie(tenantId(), _ns); } DatabaseName _dbName; @@ -894,7 +893,7 @@ public: * TODO SERVER-66887 remove this function for better clarity once call sites have been changed */ std::string dbname() const { - return _dbname ? _dbname->db() : ""; + return _dbname ? _dbname->db().toString() : ""; } const boost::optional& dbName() const { diff --git a/src/mongo/db/op_observer/op_observer_impl_test.cpp b/src/mongo/db/op_observer/op_observer_impl_test.cpp index f9d12984f34..920c4dc198a 100644 --- a/src/mongo/db/op_observer/op_observer_impl_test.cpp +++ b/src/mongo/db/op_observer/op_observer_impl_test.cpp @@ -641,7 +641,7 @@ TEST_F(OpObserverTest, OnDropCollectionInlcudesTenantId) { // Write to the oplog. { - AutoGetDb autoDb(opCtx.get(), nss.db(), MODE_X); + AutoGetDb autoDb(opCtx.get(), DatabaseName{nss.db()}, MODE_X); WriteUnitOfWork wunit(opCtx.get()); opObserver.onDropCollection( opCtx.get(), nss, uuid, 0U, OpObserver::CollectionDropType::kTwoPhase); @@ -705,7 +705,7 @@ TEST_F(OpObserverTest, OnRenameCollectionIncludesTenantIdFeatureFlagOff) { // Write to the oplog. { - AutoGetDb autoDb(opCtx.get(), sourceNss.db(), MODE_X); + AutoGetDb autoDb(opCtx.get(), DatabaseName{sourceNss.db()}, MODE_X); WriteUnitOfWork wunit(opCtx.get()); opObserver.onRenameCollection( opCtx.get(), sourceNss, targetNss, uuid, dropTargetUuid, 0U, stayTemp); @@ -741,7 +741,7 @@ TEST_F(OpObserverTest, OnRenameCollectionIncludesTenantIdFeatureFlagOn) { // Write to the oplog. { - AutoGetDb autoDb(opCtx.get(), sourceNss.db(), MODE_X); + AutoGetDb autoDb(opCtx.get(), DatabaseName{sourceNss.db()}, MODE_X); WriteUnitOfWork wunit(opCtx.get()); opObserver.onRenameCollection( opCtx.get(), sourceNss, targetNss, uuid, dropTargetUuid, 0U, stayTemp); @@ -866,7 +866,7 @@ TEST_F(OpObserverTest, ImportCollectionOplogEntryIncludesTenantId) { // Write to the oplog. { - AutoGetDb autoDb(opCtx.get(), nss.db(), MODE_X); + AutoGetDb autoDb(opCtx.get(), DatabaseName{nss.db()}, MODE_X); WriteUnitOfWork wunit(opCtx.get()); opObserver.onImportCollection(opCtx.get(), importUUID, diff --git a/src/mongo/db/pipeline/process_interface/shardsvr_process_interface.cpp b/src/mongo/db/pipeline/process_interface/shardsvr_process_interface.cpp index d177df795cf..7ebc88e64f8 100644 --- a/src/mongo/db/pipeline/process_interface/shardsvr_process_interface.cpp +++ b/src/mongo/db/pipeline/process_interface/shardsvr_process_interface.cpp @@ -435,7 +435,7 @@ ShardServerProcessInterface::expectUnshardedCollectionInScope( void ShardServerProcessInterface::checkOnPrimaryShardForDb(OperationContext* opCtx, const NamespaceString& nss) { - DatabaseShardingState::assertIsPrimaryShardForDb(opCtx, nss.db()); + DatabaseShardingState::assertIsPrimaryShardForDb(opCtx, DatabaseName{nss.db()}); } } // namespace mongo diff --git a/src/mongo/db/query/canonical_query.h b/src/mongo/db/query/canonical_query.h index 17e837e9321..5375ec42ef0 100644 --- a/src/mongo/db/query/canonical_query.h +++ b/src/mongo/db/query/canonical_query.h @@ -120,11 +120,11 @@ public: */ static Status isValidNormalized(const MatchExpression* root); - NamespaceString nss() const { + const NamespaceString& nss() const { invariant(_findCommand->getNamespaceOrUUID().nss()); return *_findCommand->getNamespaceOrUUID().nss(); } - std::string ns() const { + StringData ns() const { return nss().ns(); } diff --git a/src/mongo/db/query/planner_access.cpp b/src/mongo/db/query/planner_access.cpp index ce5ecda4874..90dcca12860 100644 --- a/src/mongo/db/query/planner_access.cpp +++ b/src/mongo/db/query/planner_access.cpp @@ -429,7 +429,7 @@ std::unique_ptr QueryPlannerAccess::makeCollectionScan( const CanonicalQuery& query, bool tailable, const QueryPlannerParams& params, int direction) { // Make the (only) node, a collection scan. auto csn = std::make_unique(); - csn->name = query.ns(); + csn->name = query.ns().toString(); csn->filter = query.root()->clone(); csn->tailable = tailable; csn->shouldTrackLatestOplogTimestamp = diff --git a/src/mongo/db/repl/cloner_test_fixture.cpp b/src/mongo/db/repl/cloner_test_fixture.cpp index 0cdbd27b18a..448e5d68e00 100644 --- a/src/mongo/db/repl/cloner_test_fixture.cpp +++ b/src/mongo/db/repl/cloner_test_fixture.cpp @@ -49,9 +49,10 @@ BSONObj ClonerTestFixture::createCountResponse(int documentCount) { } /* static */ -BSONObj ClonerTestFixture::createCursorResponse(const std::string& nss, const BSONArray& docs) { - return BSON("cursor" << BSON("id" << CursorId(0) << "ns" << nss << "firstBatch" << docs) << "ok" - << 1); +BSONObj ClonerTestFixture::createCursorResponse(StringData nss, const BSONArray& docs) { + return BSON( + "cursor" << BSON("id" << CursorId(0) << "ns" << nss.toString() << "firstBatch" << docs) + << "ok" << 1); } void ClonerTestFixture::setUp() { diff --git a/src/mongo/db/repl/cloner_test_fixture.h b/src/mongo/db/repl/cloner_test_fixture.h index 35d36d58250..e5d7d2f17a6 100644 --- a/src/mongo/db/repl/cloner_test_fixture.h +++ b/src/mongo/db/repl/cloner_test_fixture.h @@ -53,7 +53,7 @@ public: // Since the DBClient handles the cursor iterating, we assume that works for the purposes of the // cloner unit test and just use a single batch for all mock responses. - static BSONObj createCursorResponse(const std::string& nss, const BSONArray& docs); + static BSONObj createCursorResponse(StringData nss, const BSONArray& docs); protected: void setUp() override; diff --git a/src/mongo/db/repl/initial_syncer_test.cpp b/src/mongo/db/repl/initial_syncer_test.cpp index df015013477..5b5737f2f2d 100644 --- a/src/mongo/db/repl/initial_syncer_test.cpp +++ b/src/mongo/db/repl/initial_syncer_test.cpp @@ -330,7 +330,7 @@ protected: _storageInterface->dropCollFn = [this](OperationContext* opCtx, const NamespaceString& nss) { LockGuard lock(_storageInterfaceWorkDoneMutex); - _storageInterfaceWorkDone.droppedCollections.push_back(nss.ns()); + _storageInterfaceWorkDone.droppedCollections.push_back(nss.ns().toString()); return Status::OK(); }; _storageInterface->dropUserDBsFn = [this](OperationContext* opCtx) { diff --git a/src/mongo/db/repl/oplog_applier_test.cpp b/src/mongo/db/repl/oplog_applier_test.cpp index e0e21698f83..a5d4b10aecc 100644 --- a/src/mongo/db/repl/oplog_applier_test.cpp +++ b/src/mongo/db/repl/oplog_applier_test.cpp @@ -141,7 +141,8 @@ TEST_F(OplogApplierTest, GetNextApplierBatchGroupsUnpreparedApplyOpsOpWithOtherO TEST_F(OplogApplierTest, GetNextApplierBatchReturnsSystemDotViewsOpInOwnBatch) { std::vector srcOps; - srcOps.push_back(makeInsertOplogEntry(1, NamespaceString::makeSystemDotViewsNamespace(dbName))); + srcOps.push_back(makeInsertOplogEntry( + 1, NamespaceString::makeSystemDotViewsNamespace(DatabaseName{dbName}))); srcOps.push_back( makeInsertOplogEntry(2, NamespaceString::createNamespaceString_forTest(dbName, "bar"))); _applier->enqueue(opCtx(), srcOps.cbegin(), srcOps.cend()); diff --git a/src/mongo/db/repl/oplog_interface_remote.cpp b/src/mongo/db/repl/oplog_interface_remote.cpp index 1c5457ab9af..aea734b6c21 100644 --- a/src/mongo/db/repl/oplog_interface_remote.cpp +++ b/src/mongo/db/repl/oplog_interface_remote.cpp @@ -69,7 +69,7 @@ StatusWith OplogIteratorRemote::next() { OplogInterfaceRemote::OplogInterfaceRemote(HostAndPort hostAndPort, GetConnectionFn getConnection, - const std::string& collectionName, + StringData collectionName, int batchSize) : _hostAndPort(hostAndPort), _getConnection(getConnection), diff --git a/src/mongo/db/repl/oplog_interface_remote.h b/src/mongo/db/repl/oplog_interface_remote.h index 8200056f34f..5a6f7231e5e 100644 --- a/src/mongo/db/repl/oplog_interface_remote.h +++ b/src/mongo/db/repl/oplog_interface_remote.h @@ -52,7 +52,7 @@ public: OplogInterfaceRemote(HostAndPort hostAndPort, GetConnectionFn getConnection, - const std::string& collectionName, + StringData collectionName, int batchSize); std::string toString() const override; std::unique_ptr makeIterator() const override; diff --git a/src/mongo/db/repl/replication_coordinator_external_state_impl.cpp b/src/mongo/db/repl/replication_coordinator_external_state_impl.cpp index 1b659ed1b0a..23e0d77e581 100644 --- a/src/mongo/db/repl/replication_coordinator_external_state_impl.cpp +++ b/src/mongo/db/repl/replication_coordinator_external_state_impl.cpp @@ -779,7 +779,7 @@ StatusWith ReplicationCoordinatorExternalStateImpl::loadLastO BSONObj oplogEntry; if (!writeConflictRetry( - opCtx, "Load last opTime", NamespaceString::kRsOplogNamespace.ns().c_str(), [&] { + opCtx, "Load last opTime", NamespaceString::kRsOplogNamespace.ns(), [&] { return Helpers::getLast(opCtx, NamespaceString::kRsOplogNamespace, oplogEntry); })) { return StatusWith(ErrorCodes::NoMatchingDocument, diff --git a/src/mongo/db/repl/rollback_source_impl.cpp b/src/mongo/db/repl/rollback_source_impl.cpp index de16558a010..2559932a524 100644 --- a/src/mongo/db/repl/rollback_source_impl.cpp +++ b/src/mongo/db/repl/rollback_source_impl.cpp @@ -43,7 +43,7 @@ namespace repl { RollbackSourceImpl::RollbackSourceImpl(GetConnectionFn getConnection, const HostAndPort& source, - const std::string& collectionName, + StringData collectionName, int batchSize) : _getConnection(getConnection), _source(source), diff --git a/src/mongo/db/repl/rollback_source_impl.h b/src/mongo/db/repl/rollback_source_impl.h index 82c9135bf70..90147591c1e 100644 --- a/src/mongo/db/repl/rollback_source_impl.h +++ b/src/mongo/db/repl/rollback_source_impl.h @@ -55,7 +55,7 @@ public: RollbackSourceImpl(GetConnectionFn getConnection, const HostAndPort& source, - const std::string& collectionName, + StringData collectionName, int batchSize); const OplogInterface& getOplog() const override; diff --git a/src/mongo/db/repl/storage_interface_impl_test.cpp b/src/mongo/db/repl/storage_interface_impl_test.cpp index e586e013e40..f3e0fb62953 100644 --- a/src/mongo/db/repl/storage_interface_impl_test.cpp +++ b/src/mongo/db/repl/storage_interface_impl_test.cpp @@ -403,7 +403,7 @@ TEST_F(StorageInterfaceImplTest, InsertDocumentsReturnsOKWhenNoOperationsAreGive StorageInterfaceImpl storage; ASSERT_OK(storage.insertDocuments(opCtx, nss, {})); - ASSERT_OK(storage.insertDocuments(opCtx, {nss.db().toString(), *options.uuid}, {})); + ASSERT_OK(storage.insertDocuments(opCtx, {DatabaseName{nss.db()}, *options.uuid}, {})); } TEST_F(StorageInterfaceImplTest, @@ -425,7 +425,7 @@ TEST_F(StorageInterfaceImplTest, // Again, but specify the collection with its UUID. ASSERT_EQ(ErrorCodes::InternalError, storage.insertDocuments( - opCtx, {nss.db().toString(), *options.uuid}, transformInserts({op}))); + opCtx, {DatabaseName{nss.db()}, *options.uuid}, transformInserts({op}))); } TEST_F(StorageInterfaceImplTest, @@ -487,7 +487,7 @@ TEST_F(StorageInterfaceImplTest, InsertDocumentsSavesOperationsWhenCollSpecified auto op1 = makeOplogEntry({Timestamp(Seconds(1), 0), 1LL}); auto op2 = makeOplogEntry({Timestamp(Seconds(1), 0), 1LL}); ASSERT_OK(storage.insertDocuments( - opCtx, {nss.db().toString(), *options.uuid}, transformInserts({op1, op2}))); + opCtx, {DatabaseName{nss.db()}, *options.uuid}, transformInserts({op1, op2}))); // Check contents of oplog. _assertDocumentsInCollectionEquals(opCtx, nss, {op1.obj, op2.obj}); @@ -538,7 +538,7 @@ TEST_F(StorageInterfaceImplTest, InsertDocWorksWithExistingCappedCollectionSpeci StorageInterfaceImpl storage; ASSERT_OK(storage.insertDocument(opCtx, - {nss.db().toString(), *options.uuid}, + {DatabaseName{nss.db()}, *options.uuid}, {BSON("_id" << 1), Timestamp(1)}, OpTime::kUninitializedTerm)); AutoGetCollectionForReadCommand autoColl(opCtx, nss); @@ -746,11 +746,11 @@ TEST_F(StorageInterfaceImplTest, DropCollectionWorksWithMissingCollection) { auto opCtx = getOperationContext(); StorageInterfaceImpl storage; auto nss = makeNamespace(_agent); - ASSERT_FALSE(AutoGetDb(opCtx, nss.db(), MODE_IS).getDb()); + ASSERT_FALSE(AutoGetDb(opCtx, DatabaseName{nss.db()}, MODE_IS).getDb()); ASSERT_OK(storage.dropCollection(opCtx, nss)); ASSERT_FALSE(AutoGetCollectionForReadCommand(opCtx, nss).getCollection()); // Database should not be created after running dropCollection. - ASSERT_FALSE(AutoGetDb(opCtx, nss.db(), MODE_IS).getDb()); + ASSERT_FALSE(AutoGetDb(opCtx, DatabaseName{nss.db()}, MODE_IS).getDb()); } TEST_F(StorageInterfaceImplTest, DropCollectionWorksWithSystemCollection) { @@ -2553,7 +2553,7 @@ TEST_F(StorageInterfaceImplTest, FindByIdReturnsNoSuchKeyWhenDocumentIsNotFound) ASSERT_EQUALS(ErrorCodes::NoSuchKey, storage.findById(opCtx, nss, doc2["_id"]).getStatus()); ASSERT_EQUALS( ErrorCodes::NoSuchKey, - storage.findById(opCtx, {nss.db().toString(), *options.uuid}, doc2["_id"]).getStatus()); + storage.findById(opCtx, {DatabaseName{nss.db()}, *options.uuid}, doc2["_id"]).getStatus()); } TEST_F(StorageInterfaceImplTest, FindByIdReturnsDocumentWhenDocumentExists) { @@ -2575,7 +2575,7 @@ TEST_F(StorageInterfaceImplTest, FindByIdReturnsDocumentWhenDocumentExists) { ASSERT_BSONOBJ_EQ(doc2, unittest::assertGet(storage.findById(opCtx, nss, doc2["_id"]))); ASSERT_BSONOBJ_EQ(doc2, unittest::assertGet(storage.findById( - opCtx, {nss.db().toString(), *options.uuid}, doc2["_id"]))); + opCtx, {DatabaseName{nss.db()}, *options.uuid}, doc2["_id"]))); } TEST_F(StorageInterfaceImplTest, FindByIdReturnsBadStatusIfPlanExecutorFails) { @@ -2643,9 +2643,9 @@ TEST_F(StorageInterfaceImplTest, DeleteByIdReturnsNoSuchKeyWhenDocumentIsNotFoun {{doc1, Timestamp(0), OpTime::kUninitializedTerm}, {doc3, Timestamp(0), OpTime::kUninitializedTerm}})); ASSERT_EQUALS(ErrorCodes::NoSuchKey, storage.deleteById(opCtx, nss, doc2["_id"]).getStatus()); - ASSERT_EQUALS( - ErrorCodes::NoSuchKey, - storage.deleteById(opCtx, {nss.db().toString(), *options.uuid}, doc2["_id"]).getStatus()); + ASSERT_EQUALS(ErrorCodes::NoSuchKey, + storage.deleteById(opCtx, {DatabaseName{nss.db()}, *options.uuid}, doc2["_id"]) + .getStatus()); _assertDocumentsInCollectionEquals(opCtx, nss, {doc1, doc3}); } @@ -2698,7 +2698,8 @@ TEST_F(StorageInterfaceImplTest, auto opCtx = getOperationContext(); StorageInterfaceImpl storage; NamespaceString nss = NamespaceString::createNamespaceString_forTest("mydb.coll"); - NamespaceString wrongColl(nss.db(), "wrongColl"_sd); + NamespaceString wrongColl = + NamespaceString::createNamespaceString_forTest(DatabaseName{nss.db()}, "wrongColl"_sd); ASSERT_OK(storage.createCollection(opCtx, nss, generateOptionsWithUuid())); auto doc = BSON("_id" << 0 << "x" << 1); auto status = storage.upsertById(opCtx, wrongColl, doc["_id"], doc); @@ -2732,7 +2733,7 @@ TEST_F(StorageInterfaceImplTest, UpsertSingleDocumentReplacesExistingDocumentInC // Again, but specify the collection's UUID. ASSERT_OK(storage.upsertById( - opCtx, {nss.db().toString(), *options.uuid}, originalDoc["_id"], BSON("x" << 200))); + opCtx, {DatabaseName{nss.db()}, *options.uuid}, originalDoc["_id"], BSON("x" << 200))); _assertDocumentsInCollectionEquals(opCtx, nss, {BSON("_id" << 0 << "x" << 0), @@ -2765,7 +2766,7 @@ TEST_F(StorageInterfaceImplTest, UpsertSingleDocumentInsertsNewDocumentInCollect BSON("_id" << 1 << "x" << 100)}); ASSERT_OK(storage.upsertById(opCtx, - {nss.db().toString(), *options.uuid}, + {DatabaseName{nss.db()}, *options.uuid}, BSON("" << 3).firstElement(), BSON("x" << 300))); _assertDocumentsInCollectionEquals(opCtx, @@ -2805,7 +2806,7 @@ TEST_F(StorageInterfaceImplTest, BSON("_id" << 2 << "x" << 2)}); ASSERT_OK(storage.upsertById( - opCtx, {nss.db().toString(), *options.uuid}, originalDoc["_id"], BSON("x" << 200))); + opCtx, {DatabaseName{nss.db()}, *options.uuid}, originalDoc["_id"], BSON("x" << 200))); _assertDocumentsInCollectionEquals(opCtx, nss, {BSON("_id" << 0 << "x" << 0), @@ -2828,7 +2829,7 @@ TEST_F(StorageInterfaceImplTest, UpsertSingleDocumentReturnsFailedToParseOnNonSi "Unable to update document with a non-simple _id query:"); ASSERT_EQ(storage.upsertById(opCtx, - {nss.db().toString(), *options.uuid}, + {DatabaseName{nss.db()}, *options.uuid}, BSON("" << BSON("$gt" << 3)).firstElement(), BSON("x" << 100)), ErrorCodes::InvalidIdField); @@ -2850,7 +2851,7 @@ TEST_F(StorageInterfaceImplTest, ASSERT_STRING_CONTAINS(status.reason(), "Unable to update document in a collection without an _id index."); - ASSERT_EQ(storage.upsertById(opCtx, {nss.db().toString(), *options.uuid}, doc["_id"], doc), + ASSERT_EQ(storage.upsertById(opCtx, {DatabaseName{nss.db()}, *options.uuid}, doc["_id"], doc), ErrorCodes::IndexNotFound); } @@ -2872,7 +2873,7 @@ TEST_F(StorageInterfaceImplTest, "update specified as an array"); ASSERT_THROWS_CODE(storage.upsertById(opCtx, - {nss.db().toString(), *options.uuid}, + {DatabaseName{nss.db()}, *options.uuid}, BSON("" << 1).firstElement(), unknownUpdateOp), DBException, @@ -2975,7 +2976,8 @@ TEST_F(StorageInterfaceImplTest, DeleteByFilterReturnsNamespaceNotFoundWhenColle auto opCtx = getOperationContext(); StorageInterfaceImpl storage; NamespaceString nss = NamespaceString::createNamespaceString_forTest("mydb.coll"); - NamespaceString wrongColl(nss.db(), "wrongColl"_sd); + NamespaceString wrongColl = + NamespaceString::createNamespaceString_forTest(DatabaseName{nss.db()}, "wrongColl"_sd); ASSERT_OK(storage.createCollection(opCtx, nss, generateOptionsWithUuid())); auto filter = BSON("x" << 1); auto status = storage.deleteByFilter(opCtx, wrongColl, filter); @@ -3145,7 +3147,8 @@ TEST_F(StorageInterfaceImplTest, auto opCtx = getOperationContext(); StorageInterfaceImpl storage; auto nss = makeNamespace(_agent); - NamespaceString wrongColl(nss.db(), "wrongColl"_sd); + NamespaceString wrongColl = + NamespaceString::createNamespaceString_forTest(DatabaseName{nss.db()}, "wrongColl"_sd); ASSERT_OK(storage.createCollection(opCtx, nss, generateOptionsWithUuid())); ASSERT_EQUALS(ErrorCodes::NamespaceNotFound, storage.getCollectionCount(opCtx, wrongColl).getStatus()); @@ -3188,7 +3191,8 @@ TEST_F(StorageInterfaceImplTest, auto opCtx = getOperationContext(); StorageInterfaceImpl storage; auto nss = makeNamespace(_agent); - NamespaceString wrongColl(nss.db(), "wrongColl"_sd); + NamespaceString wrongColl = + NamespaceString::createNamespaceString_forTest(DatabaseName{nss.db()}, "wrongColl"_sd); ASSERT_OK(storage.createCollection(opCtx, nss, generateOptionsWithUuid())); ASSERT_EQUALS(ErrorCodes::NamespaceNotFound, storage.setCollectionCount(opCtx, wrongColl, 3)); } @@ -3206,7 +3210,8 @@ TEST_F(StorageInterfaceImplTest, auto opCtx = getOperationContext(); StorageInterfaceImpl storage; auto nss = makeNamespace(_agent); - NamespaceString wrongColl(nss.db(), "wrongColl"_sd); + NamespaceString wrongColl = + NamespaceString::createNamespaceString_forTest(DatabaseName{nss.db()}, "wrongColl"_sd); ASSERT_OK(storage.createCollection(opCtx, nss, generateOptionsWithUuid())); ASSERT_EQUALS(ErrorCodes::NamespaceNotFound, storage.getCollectionSize(opCtx, wrongColl).getStatus()); @@ -3249,7 +3254,8 @@ TEST_F(StorageInterfaceImplTest, SetIndexIsMultikeyReturnsNamespaceNotFoundForMi auto opCtx = getOperationContext(); StorageInterfaceImpl storage; auto nss = makeNamespace(_agent); - NamespaceString wrongColl(nss.db(), "wrongColl"_sd); + NamespaceString wrongColl = + NamespaceString::createNamespaceString_forTest(DatabaseName{nss.db()}, "wrongColl"_sd); ASSERT_OK(storage.createCollection(opCtx, nss, CollectionOptions())); ASSERT_EQUALS( ErrorCodes::NamespaceNotFound, @@ -3262,7 +3268,8 @@ TEST_F(StorageInterfaceImplTest, SetIndexIsMultikeyLooksUpCollectionByUUID) { auto nss = makeNamespace(_agent); auto options = generateOptionsWithUuid(); ASSERT_OK(storage.createCollection(opCtx, nss, options)); - NamespaceString wrongColl(nss.db(), "wrongColl"_sd); + NamespaceString wrongColl = + NamespaceString::createNamespaceString_forTest(DatabaseName{nss.db()}, "wrongColl"_sd); ASSERT_EQUALS(ErrorCodes::IndexNotFound, storage.setIndexIsMultikey( opCtx, wrongColl, *options.uuid, "foo", {}, {}, Timestamp(3, 3))); diff --git a/src/mongo/db/repl/tenant_collection_cloner.cpp b/src/mongo/db/repl/tenant_collection_cloner.cpp index ff5899c20ef..7bb28eb869e 100644 --- a/src/mongo/db/repl/tenant_collection_cloner.cpp +++ b/src/mongo/db/repl/tenant_collection_cloner.cpp @@ -104,7 +104,7 @@ TenantCollectionCloner::TenantCollectionCloner(const NamespaceString& sourceNss, invariant(ClonerUtils::isNamespaceForTenant(sourceNss, tenantId)); invariant(collectionOptions.uuid); _sourceDbAndUuid = NamespaceStringOrUUID(sourceNss.dbName(), *collectionOptions.uuid); - _stats.ns = _sourceNss.ns(); + _stats.ns = _sourceNss.ns().toString(); } BaseCloner::ClonerStages TenantCollectionCloner::getStages() { diff --git a/src/mongo/db/repl/tenant_database_cloner.cpp b/src/mongo/db/repl/tenant_database_cloner.cpp index ca06222ceaa..6551c7838d9 100644 --- a/src/mongo/db/repl/tenant_database_cloner.cpp +++ b/src/mongo/db/repl/tenant_database_cloner.cpp @@ -304,7 +304,7 @@ void TenantDatabaseCloner::postStage() { _stats.collectionStats.reserve(_collections.size()); for (const auto& coll : _collections) { _stats.collectionStats.emplace_back(); - _stats.collectionStats.back().ns = coll.first.ns(); + _stats.collectionStats.back().ns = coll.first.ns().toString(); } } for (const auto& coll : _collections) { diff --git a/src/mongo/db/repl/tenant_file_importer_service.cpp b/src/mongo/db/repl/tenant_file_importer_service.cpp index b88437df094..9764eb86820 100644 --- a/src/mongo/db/repl/tenant_file_importer_service.cpp +++ b/src/mongo/db/repl/tenant_file_importer_service.cpp @@ -318,7 +318,7 @@ void TenantFileImporterService::_voteImportedFiles(OperationContext* opCtx, auto voteResponse = replCoord->runCmdOnPrimaryAndAwaitResponse( opCtx, - DatabaseName::kAdmin.db(), + DatabaseName::kAdmin.db().toString(), cmd.toBSON({}), [](executor::TaskExecutor::CallbackHandle handle) {}, [](executor::TaskExecutor::CallbackHandle handle) {}); diff --git a/src/mongo/db/repl/tenant_migration_access_blocker_util.cpp b/src/mongo/db/repl/tenant_migration_access_blocker_util.cpp index 95aeb6312fe..c7f16a6604b 100644 --- a/src/mongo/db/repl/tenant_migration_access_blocker_util.cpp +++ b/src/mongo/db/repl/tenant_migration_access_blocker_util.cpp @@ -714,7 +714,7 @@ boost::optional extractTenantFromDatabaseName(const DatabaseName& d return boost::none; } - return dbName.db().substr(0, pos); + return dbName.db().substr(0, pos).toString(); } } // namespace tenant_migration_access_blocker diff --git a/src/mongo/db/repl/tenant_migration_access_blocker_util_test.cpp b/src/mongo/db/repl/tenant_migration_access_blocker_util_test.cpp index 229c7981668..2d3a99956c1 100644 --- a/src/mongo/db/repl/tenant_migration_access_blocker_util_test.cpp +++ b/src/mongo/db/repl/tenant_migration_access_blocker_util_test.cpp @@ -95,7 +95,8 @@ TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveShardMergeTrueWithDonor) { std::make_shared(getServiceContext(), UUID::gen()); TenantMigrationAccessBlockerRegistry::get(getServiceContext()) .addGlobalDonorAccessBlocker(donorMtab); - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), "local"_sd)); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kLocal)); ASSERT(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), kTenantDB)); } @@ -129,7 +130,8 @@ TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveShardMergeTrueWithBoth) { TenantMigrationAccessBlockerRegistry::get(getServiceContext()) .addGlobalDonorAccessBlocker(donorMtab); // Access blocker do not impact ns without tenants. - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), "config"_sd)); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kConfig)); ASSERT(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), kTenantDB)); } @@ -138,7 +140,8 @@ TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveTenantMigrationDonorFalseF std::make_shared(getServiceContext(), UUID::gen()); TenantMigrationAccessBlockerRegistry::get(getServiceContext()).add(kTenantId, donorMtab); - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), StringData())); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kEmpty)); } TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveShardMergeDonorFalseForNoDbName) { @@ -146,14 +149,16 @@ TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveShardMergeDonorFalseForNoD std::make_shared(getServiceContext(), UUID::gen()); TenantMigrationAccessBlockerRegistry::get(getServiceContext()) .addGlobalDonorAccessBlocker(donorMtab); - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), StringData())); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kEmpty)); } TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveShardMergeRecipientFalseForNoDbName) { auto recipientMtab = std::make_shared(getServiceContext(), UUID::gen()); TenantMigrationAccessBlockerRegistry::get(getServiceContext()).add(kTenantId, recipientMtab); - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), StringData())); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kEmpty)); } TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveTenantMigrationFalseForUnrelatedDb) { @@ -165,7 +170,8 @@ TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveTenantMigrationFalseForUnr std::make_shared(getServiceContext(), UUID::gen()); TenantMigrationAccessBlockerRegistry::get(getServiceContext()).add(kTenantId, donorMtab); - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), "config"_sd)); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kConfig)); } TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveTenantMigrationFalseAfterRemoveWithBoth) { @@ -202,20 +208,23 @@ TEST_F(TenantMigrationAccessBlockerUtilTest, HasActiveShardMergeFalseAfterRemove .addGlobalDonorAccessBlocker(donorMtab); ASSERT(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), kTenantDB)); - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), "admin"_sd)); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kAdmin)); // Remove donor, should still be a migration for the tenants migrating to the recipient. TenantMigrationAccessBlockerRegistry::get(getServiceContext()) .removeAccessBlockersForMigration(migrationId, TenantMigrationAccessBlocker::BlockerType::kDonor); ASSERT(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), kTenantDB)); - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), "admin"_sd)); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kAdmin)); // Remove recipient, there should be no migration. TenantMigrationAccessBlockerRegistry::get(getServiceContext()) .remove(kTenantId, TenantMigrationAccessBlocker::BlockerType::kRecipient); ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), kTenantDB)); - ASSERT_FALSE(tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), "admin"_sd)); + ASSERT_FALSE( + tenant_migration_access_blocker::hasActiveTenantMigration(opCtx(), DatabaseName::kAdmin)); } TEST_F(TenantMigrationAccessBlockerUtilTest, TestValidateNssBeingMigrated) { diff --git a/src/mongo/db/s/analyze_shard_key_cmd_util.cpp b/src/mongo/db/s/analyze_shard_key_cmd_util.cpp index 1c554a800fe..4bfbe6c84c5 100644 --- a/src/mongo/db/s/analyze_shard_key_cmd_util.cpp +++ b/src/mongo/db/s/analyze_shard_key_cmd_util.cpp @@ -705,7 +705,8 @@ std::pair generateSplitPoints(OperationContext* opCtx, str::stream() << "Cannot analyze a shard key for a non-existing collection", origCollUuid); // Perform best-effort validation that the collection has not been dropped and recreated. - uassert(CollectionUUIDMismatchInfo(nss.db(), collUuid, nss.coll().toString(), boost::none), + uassert(CollectionUUIDMismatchInfo( + DatabaseName{nss.db()}, collUuid, nss.coll().toString(), boost::none), str::stream() << "Found that the collection UUID has changed from " << collUuid << " to " << origCollUuid << " since the command started", origCollUuid == collUuid); @@ -823,7 +824,8 @@ KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* o str::stream() << "Cannot analyze a shard key for a non-existing collection", collection); // Perform best-effort validation that the collection has not been dropped and recreated. - uassert(CollectionUUIDMismatchInfo(nss.db(), collUuid, nss.coll().toString(), boost::none), + uassert(CollectionUUIDMismatchInfo( + DatabaseName{nss.db()}, collUuid, nss.coll().toString(), boost::none), str::stream() << "Found that the collection UUID has changed from " << collUuid << " to " << collection->uuid() << " since the command started", collection->uuid() == collUuid); diff --git a/src/mongo/db/s/balancer/migration_test_fixture.cpp b/src/mongo/db/s/balancer/migration_test_fixture.cpp index e5b51181003..ed45e996856 100644 --- a/src/mongo/db/s/balancer/migration_test_fixture.cpp +++ b/src/mongo/db/s/balancer/migration_test_fixture.cpp @@ -86,9 +86,9 @@ void MigrationTestFixture::setUpZones(const NamespaceString& collName, const StringMap& zoneChunkRanges) { for (auto const& zoneChunkRange : zoneChunkRanges) { BSONObjBuilder zoneDocBuilder; - zoneDocBuilder.append( - "_id", - BSON(TagsType::ns(collName.ns()) << TagsType::min(zoneChunkRange.second.getMin()))); + zoneDocBuilder.append("_id", + BSON(TagsType::ns(collName.ns().toString()) + << TagsType::min(zoneChunkRange.second.getMin()))); zoneDocBuilder.append(TagsType::ns(), collName.ns()); zoneDocBuilder.append(TagsType::min(), zoneChunkRange.second.getMin()); zoneDocBuilder.append(TagsType::max(), zoneChunkRange.second.getMax()); diff --git a/src/mongo/db/s/config/configsvr_add_shard_command.cpp b/src/mongo/db/s/config/configsvr_add_shard_command.cpp index a9ef2a14dc2..11ccdd19b06 100644 --- a/src/mongo/db/s/config/configsvr_add_shard_command.cpp +++ b/src/mongo/db/s/config/configsvr_add_shard_command.cpp @@ -86,7 +86,7 @@ Status notifyShardsOfSecondShardIfNeeded(OperationContext* opCtx) { // Set the cluster parameter to disallow direct writes to shards ConfigsvrSetClusterParameter configsvrSetClusterParameter( BSON("shardedClusterCardinalityForDirectConns" << BSON("hasTwoOrMoreShards" << true))); - configsvrSetClusterParameter.setDbName(DatabaseName(boost::none, "admin")); + configsvrSetClusterParameter.setDbName(DatabaseName::kAdmin); const auto cmdResponse = shardRegistry->getConfigShard()->runCommandWithFixedRetryAttempts( opCtx, diff --git a/src/mongo/db/s/config/configsvr_remove_tags_command.cpp b/src/mongo/db/s/config/configsvr_remove_tags_command.cpp index 8f5fd5f7ec3..8dd75292aa7 100644 --- a/src/mongo/db/s/config/configsvr_remove_tags_command.cpp +++ b/src/mongo/db/s/config/configsvr_remove_tags_command.cpp @@ -95,7 +95,7 @@ public: uassertStatusOK(catalogClient->removeConfigDocuments( newOpCtxPtr.get(), TagsType::ConfigNS, - BSON(TagsType::ns(nss.ns())), + BSON(TagsType::ns(nss.ns().toString())), ShardingCatalogClient::kLocalWriteConcern)); } diff --git a/src/mongo/db/s/config/initial_split_policy_test.cpp b/src/mongo/db/s/config/initial_split_policy_test.cpp index 923a59e01ea..648cbcb9719 100644 --- a/src/mongo/db/s/config/initial_split_policy_test.cpp +++ b/src/mongo/db/s/config/initial_split_policy_test.cpp @@ -394,8 +394,8 @@ public: TagsType makeTag(const ChunkRange range, std::string zoneName) { BSONObjBuilder tagDocBuilder; - tagDocBuilder.append("_id", - BSON(TagsType::ns(nss().ns()) << TagsType::min(range.getMin()))); + tagDocBuilder.append( + "_id", BSON(TagsType::ns(nss().ns().toString()) << TagsType::min(range.getMin()))); tagDocBuilder.append(TagsType::ns(), nss().ns()); tagDocBuilder.append(TagsType::min(), range.getMin()); tagDocBuilder.append(TagsType::max(), range.getMax()); diff --git a/src/mongo/db/s/config/sharding_catalog_manager_assign_key_range_to_zone_test.cpp b/src/mongo/db/s/config/sharding_catalog_manager_assign_key_range_to_zone_test.cpp index 377d17292ff..e486fb7daad 100644 --- a/src/mongo/db/s/config/sharding_catalog_manager_assign_key_range_to_zone_test.cpp +++ b/src/mongo/db/s/config/sharding_catalog_manager_assign_key_range_to_zone_test.cpp @@ -225,12 +225,13 @@ TEST_F(AssignKeyRangeToZoneTestFixture, RemoveZoneWithDollarPrefixedShardKeysSho // Manually insert a zone with illegal keys in order to bypass the checks performed by // assignKeyRangeToZone - BSONObj updateQuery(BSON("_id" << BSON(TagsType::ns(shardedNS().ns()) + BSONObj updateQuery(BSON("_id" << BSON(TagsType::ns(shardedNS().ns().toString()) << TagsType::min(zoneWithDollarKeys.getMin())))); BSONObjBuilder updateBuilder; - updateBuilder.append( - "_id", BSON(TagsType::ns(shardedNS().ns()) << TagsType::min(zoneWithDollarKeys.getMin()))); + updateBuilder.append("_id", + BSON(TagsType::ns(shardedNS().ns().toString()) + << TagsType::min(zoneWithDollarKeys.getMin()))); updateBuilder.append(TagsType::ns(), shardedNS().ns()); updateBuilder.append(TagsType::min(), zoneWithDollarKeys.getMin()); updateBuilder.append(TagsType::max(), zoneWithDollarKeys.getMax()); diff --git a/src/mongo/db/s/config/sharding_catalog_manager_merge_chunks_test.cpp b/src/mongo/db/s/config/sharding_catalog_manager_merge_chunks_test.cpp index 1f260d2fea4..2dfc3f40312 100644 --- a/src/mongo/db/s/config/sharding_catalog_manager_merge_chunks_test.cpp +++ b/src/mongo/db/s/config/sharding_catalog_manager_merge_chunks_test.cpp @@ -893,7 +893,7 @@ protected: size_t numMerges = 0; for (const auto& chunkDiff : chunksDiff) { BSONObjBuilder query; - query << ChangeLogType::what("merge") << ChangeLogType::ns(nss.ns()); + query << ChangeLogType::what("merge") << ChangeLogType::ns(nss.ns().toString()); chunkDiff.getVersion().serialize("details.mergedVersion", &query); auto response = assertGet(getConfigShard()->exhaustiveFindOnConfig( diff --git a/src/mongo/db/s/config/sharding_catalog_manager_zone_operations.cpp b/src/mongo/db/s/config/sharding_catalog_manager_zone_operations.cpp index 4fd943c3bfb..aeb3bcb7522 100644 --- a/src/mongo/db/s/config/sharding_catalog_manager_zone_operations.cpp +++ b/src/mongo/db/s/config/sharding_catalog_manager_zone_operations.cpp @@ -74,7 +74,7 @@ Status checkForOverlappingZonedKeyRange(OperationContext* opCtx, kConfigPrimarySelector, repl::ReadConcernLevel::kLocalReadConcern, TagsType::ConfigNS, - BSON(TagsType::ns(nss.ns())), + BSON(TagsType::ns(nss.ns().toString())), BSONObj(), 0); if (!tagStatus.isOK()) { @@ -362,7 +362,7 @@ void ShardingCatalogManager::assignKeyRangeToZone(OperationContext* opCtx, uassertStatusOK(_localCatalogClient->updateConfigDocument( opCtx, TagsType::ConfigNS, - BSON(TagsType::ns(nss.ns()) << TagsType::min(actualRange.getMin())), + BSON(TagsType::ns(nss.ns().toString()) << TagsType::min(actualRange.getMin())), updateBuilder.obj(), true, kNoWaitWriteConcern)); diff --git a/src/mongo/db/s/configure_query_analyzer_cmd.cpp b/src/mongo/db/s/configure_query_analyzer_cmd.cpp index b212ab96f49..5432dbbdf79 100644 --- a/src/mongo/db/s/configure_query_analyzer_cmd.cpp +++ b/src/mongo/db/s/configure_query_analyzer_cmd.cpp @@ -62,7 +62,7 @@ constexpr int kMaxSampleRate = 1'000'000; StatusWith validateCollectionOptionsOnPrimaryShard(OperationContext* opCtx, const NamespaceString& nss) { ListCollections listCollections; - listCollections.setDbName(nss.db()); + listCollections.setDbName(DatabaseName{nss.db()}); listCollections.setFilter(BSON("name" << nss.coll())); auto listCollectionsCmdObj = CommandHelpers::filterCommandRequestForPassthrough(listCollections.toBSON({})); diff --git a/src/mongo/db/s/drop_database_coordinator.cpp b/src/mongo/db/s/drop_database_coordinator.cpp index 42396bef6b3..6189f2ecbf4 100644 --- a/src/mongo/db/s/drop_database_coordinator.cpp +++ b/src/mongo/db/s/drop_database_coordinator.cpp @@ -407,7 +407,7 @@ ExecutorFuture DropDatabaseCoordinator::_runImpl( } auto dropDatabaseParticipantCmd = ShardsvrDropDatabaseParticipant(); - dropDatabaseParticipantCmd.setDbName(_dbName); + dropDatabaseParticipantCmd.setDbName(DatabaseName{_dbName}); const auto cmdObj = CommandHelpers::appendMajorityWriteConcern( dropDatabaseParticipantCmd.toBSON({})); @@ -494,7 +494,7 @@ ExecutorFuture DropDatabaseCoordinator::_runImpl( FlushDatabaseCacheUpdatesWithWriteConcern flushDbCacheUpdatesCmd( _dbName.toString()); flushDbCacheUpdatesCmd.setSyncFromConfig(true); - flushDbCacheUpdatesCmd.setDbName(_dbName); + flushDbCacheUpdatesCmd.setDbName(DatabaseName{_dbName}); IgnoreAPIParametersBlock ignoreApiParametersBlock{opCtx}; sharding_ddl_util::sendAuthenticatedCommandToShards( diff --git a/src/mongo/db/s/flush_database_cache_updates_command.cpp b/src/mongo/db/s/flush_database_cache_updates_command.cpp index 3509a8e9303..33d2f57b374 100644 --- a/src/mongo/db/s/flush_database_cache_updates_command.cpp +++ b/src/mongo/db/s/flush_database_cache_updates_command.cpp @@ -143,7 +143,7 @@ public: "Can't call _flushDatabaseCacheUpdates if in read-only mode", !opCtx->readOnly()); - if (_dbName() == DatabaseName::kAdmin || _dbName() == DatabaseName::kConfig) { + if (_dbName() == DatabaseName::kAdmin.db() || _dbName() == DatabaseName::kConfig.db()) { // The admin and config databases have fixed metadata that does not need to be // refreshed. @@ -157,7 +157,8 @@ public: 1, "Inserting a database collection entry with fixed metadata", "db"_attr = _dbName()); - uassertStatusOK(insertDatabaseEntryForBackwardCompatibility(opCtx, _dbName())); + uassertStatusOK(insertDatabaseEntryForBackwardCompatibility( + opCtx, DatabaseName{_dbName()})); } return; @@ -166,7 +167,7 @@ public: boost::optional> criticalSectionSignal; { - AutoGetDb autoDb(opCtx, _dbName(), MODE_IS); + AutoGetDb autoDb(opCtx, DatabaseName{_dbName()}, MODE_IS); // If the primary is in the critical section, secondaries must wait for the commit // to finish on the primary in case a secondary's caller has an afterClusterTime diff --git a/src/mongo/db/s/global_index/global_index_cloning_service_test.cpp b/src/mongo/db/s/global_index/global_index_cloning_service_test.cpp index 96b8e60993a..f85acd5834a 100644 --- a/src/mongo/db/s/global_index/global_index_cloning_service_test.cpp +++ b/src/mongo/db/s/global_index/global_index_cloning_service_test.cpp @@ -307,7 +307,7 @@ public: replaceFetcherResultList(std::move(fetcherResults)); CreateGlobalIndex createGlobalIndex(_indexCollectionUUID); - createGlobalIndex.setDbName({boost::none, "admin"}); + createGlobalIndex.setDbName(DatabaseName::kAdmin); BSONObj cmdResult; auto success = client.runCommand({boost::none, "admin"}, createGlobalIndex.toBSON({}), cmdResult); diff --git a/src/mongo/db/s/global_index/global_index_inserter.cpp b/src/mongo/db/s/global_index/global_index_inserter.cpp index 6a7ba103788..8ebadf1dd90 100644 --- a/src/mongo/db/s/global_index/global_index_inserter.cpp +++ b/src/mongo/db/s/global_index/global_index_inserter.cpp @@ -91,7 +91,7 @@ void GlobalIndexInserter::processDoc(OperationContext* opCtx, InsertGlobalIndexKey globalIndexEntryInsert(_indexUUID); // Note: dbName is unused by command but required by idl. - globalIndexEntryInsert.setDbName({boost::none, "admin"}); + globalIndexEntryInsert.setDbName(DatabaseName::kAdmin); globalIndexEntryInsert.setGlobalIndexKeyEntry( GlobalIndexKeyEntry(indexKeyValues, documentKey)); diff --git a/src/mongo/db/s/global_index/global_index_inserter_test.cpp b/src/mongo/db/s/global_index/global_index_inserter_test.cpp index c65ca491f74..ee70e6edb67 100644 --- a/src/mongo/db/s/global_index/global_index_inserter_test.cpp +++ b/src/mongo/db/s/global_index/global_index_inserter_test.cpp @@ -76,7 +76,7 @@ public: _executor = makeTaskExecutorForCloner(); CreateGlobalIndex createGlobalIndex(_indexUUID); - createGlobalIndex.setDbName({boost::none, "admin"}); + createGlobalIndex.setDbName(DatabaseName::kAdmin); BSONObj cmdResult; auto success = client.runCommand({boost::none, "admin"}, createGlobalIndex.toBSON({}), cmdResult); diff --git a/src/mongo/db/s/migration_destination_manager.cpp b/src/mongo/db/s/migration_destination_manager.cpp index 81a062c2491..34467541e38 100644 --- a/src/mongo/db/s/migration_destination_manager.cpp +++ b/src/mongo/db/s/migration_destination_manager.cpp @@ -1700,7 +1700,7 @@ bool MigrationDestinationManager::_applyMigrateOp(OperationContext* opCtx, const if (xfer["deleted"].isABSONObj()) { boost::optional rs; if (serverGlobalParams.moveParanoia) { - rs.emplace("moveChunk", _nss.ns(), "removedDuring"); + rs.emplace("moveChunk", _nss.ns().toString(), "removedDuring"); } BSONObjIterator i(xfer["deleted"].Obj()); diff --git a/src/mongo/db/s/move_primary/move_primary_donor_service.cpp b/src/mongo/db/s/move_primary/move_primary_donor_service.cpp index ae82cda7b07..486dfbc2f93 100644 --- a/src/mongo/db/s/move_primary/move_primary_donor_service.cpp +++ b/src/mongo/db/s/move_primary/move_primary_donor_service.cpp @@ -277,7 +277,7 @@ void MovePrimaryDonorExternalState::syncDataOnRecipient(OperationContext* opCtx, boost::optional timestamp) { MovePrimaryRecipientSyncData request; request.setMovePrimaryCommonMetadata(getMetadata()); - request.setDbName(getMetadata().getDatabaseName().db()); + request.setDbName(DatabaseName{getMetadata().getDatabaseName().db()}); if (timestamp) { request.setReturnAfterReachingDonorTimestamp(*timestamp); } @@ -287,14 +287,14 @@ void MovePrimaryDonorExternalState::syncDataOnRecipient(OperationContext* opCtx, void MovePrimaryDonorExternalState::abortMigrationOnRecipient(OperationContext* opCtx) { MovePrimaryRecipientAbortMigration request; request.setMovePrimaryCommonMetadata(getMetadata()); - request.setDbName(getMetadata().getDatabaseName().db()); + request.setDbName(DatabaseName{getMetadata().getDatabaseName().db()}); _runCommandOnRecipient(opCtx, request.toBSON({})); } void MovePrimaryDonorExternalState::forgetMigrationOnRecipient(OperationContext* opCtx) { MovePrimaryRecipientForgetMigration request; request.setMovePrimaryCommonMetadata(getMetadata()); - request.setDbName(getMetadata().getDatabaseName().db()); + request.setDbName(DatabaseName{getMetadata().getDatabaseName().db()}); _runCommandOnRecipient(opCtx, request.toBSON({})); } @@ -364,7 +364,7 @@ bool MovePrimaryDonor::_matchesArguments(const std::shared_ptr const DatabaseName& dbName, const ShardId& toShard) { const auto& metadata = instance->getMetadata(); - if (dbName != metadata.getDatabaseName().db()) { + if (dbName != metadata.getDatabaseName().dbName()) { return false; } if (toShard.toString() != metadata.getToShardName()) { diff --git a/src/mongo/db/s/move_primary_coordinator.cpp b/src/mongo/db/s/move_primary_coordinator.cpp index f8a214246e3..89b2f12b9a0 100644 --- a/src/mongo/db/s/move_primary_coordinator.cpp +++ b/src/mongo/db/s/move_primary_coordinator.cpp @@ -592,7 +592,7 @@ std::vector MovePrimaryCoordinator::cloneDataToRecipient( const auto cloneResponse = toShard->runCommand(opCtx, ReadPreferenceSetting(ReadPreference::PrimaryOnly), - DatabaseName::kAdmin.db(), + DatabaseName::kAdmin.db().toString(), cloneCommand, Shard::RetryPolicy::kNoRetry); @@ -641,7 +641,7 @@ void MovePrimaryCoordinator::commitMetadataToConfig( const auto commitResponse = config->runCommandWithFixedRetryAttempts(opCtx, ReadPreferenceSetting(ReadPreference::PrimaryOnly), - DatabaseName::kAdmin.db(), + DatabaseName::kAdmin.db().toString(), commitCommand, Shard::RetryPolicy::kIdempotent); diff --git a/src/mongo/db/s/move_primary_source_manager.cpp b/src/mongo/db/s/move_primary_source_manager.cpp index fcf62395449..5ad4ac0426a 100644 --- a/src/mongo/db/s/move_primary_source_manager.cpp +++ b/src/mongo/db/s/move_primary_source_manager.cpp @@ -345,7 +345,8 @@ Status MovePrimarySourceManager::_commitOnConfig(OperationContext* opCtx, notifyChangeStreamsOnMovePrimary(opCtx, getNss().dbName(), _fromShard, _toShard); const auto commitStatus = [&] { - ConfigsvrCommitMovePrimary commitRequest(_dbname, expectedDbVersion, _toShard); + ConfigsvrCommitMovePrimary commitRequest( + DatabaseName{_dbname}, expectedDbVersion, _toShard); commitRequest.setDbName(DatabaseName::kAdmin); const auto commitResponse = @@ -465,7 +466,7 @@ Status MovePrimarySourceManager::cleanStaleData(OperationContext* opCtx) { DBDirectClient client(opCtx); for (auto& coll : _clonedColls) { BSONObj dropCollResult; - client.runCommand(_dbname, BSON("drop" << coll.coll()), dropCollResult); + client.runCommand(DatabaseName{_dbname}, BSON("drop" << coll.coll()), dropCollResult); Status dropStatus = getStatusFromCommandResult(dropCollResult); if (!dropStatus.isOK()) { LOGV2(22045, diff --git a/src/mongo/db/s/move_timing_helper.cpp b/src/mongo/db/s/move_timing_helper.cpp index 1494da2882e..2d78ba65b8f 100644 --- a/src/mongo/db/s/move_timing_helper.cpp +++ b/src/mongo/db/s/move_timing_helper.cpp @@ -45,7 +45,7 @@ namespace mongo { MoveTimingHelper::MoveTimingHelper(OperationContext* opCtx, const std::string& where, - const std::string& ns, + StringData ns, const boost::optional& min, const boost::optional& max, int totalNumSteps, diff --git a/src/mongo/db/s/move_timing_helper.h b/src/mongo/db/s/move_timing_helper.h index e7f0de9ca2a..763268bab05 100644 --- a/src/mongo/db/s/move_timing_helper.h +++ b/src/mongo/db/s/move_timing_helper.h @@ -44,7 +44,7 @@ class MoveTimingHelper { public: MoveTimingHelper(OperationContext* opCtx, const std::string& where, - const std::string& ns, + StringData ns, const boost::optional& min, const boost::optional& max, int totalNumSteps, diff --git a/src/mongo/db/s/op_observer_sharding_impl.cpp b/src/mongo/db/s/op_observer_sharding_impl.cpp index ee75c265bce..b1cb1fa739c 100644 --- a/src/mongo/db/s/op_observer_sharding_impl.cpp +++ b/src/mongo/db/s/op_observer_sharding_impl.cpp @@ -121,7 +121,7 @@ void OpObserverShardingImpl::shardObserveInsertsOp( auto* const css = shardingWriteRouter.getCss(); css->checkShardVersionOrThrow(opCtx); - DatabaseShardingState::assertMatchingDbVersion(opCtx, nss.db()); + DatabaseShardingState::assertMatchingDbVersion(opCtx, DatabaseName{nss.db()}); auto* const csr = checked_cast(css); auto metadata = csr->getCurrentMetadataIfKnown(); @@ -163,7 +163,7 @@ void OpObserverShardingImpl::shardObserveUpdateOp(OperationContext* opCtx, const bool inMultiDocumentTransaction) { auto* const css = shardingWriteRouter.getCss(); css->checkShardVersionOrThrow(opCtx); - DatabaseShardingState::assertMatchingDbVersion(opCtx, nss.db()); + DatabaseShardingState::assertMatchingDbVersion(opCtx, DatabaseName{nss.db()}); auto* const csr = checked_cast(css); auto metadata = csr->getCurrentMetadataIfKnown(); @@ -199,7 +199,7 @@ void OpObserverShardingImpl::shardObserveDeleteOp(OperationContext* opCtx, const bool inMultiDocumentTransaction) { auto* const css = shardingWriteRouter.getCss(); css->checkShardVersionOrThrow(opCtx); - DatabaseShardingState::assertMatchingDbVersion(opCtx, nss.db()); + DatabaseShardingState::assertMatchingDbVersion(opCtx, DatabaseName{nss.db()}); auto* const csr = checked_cast(css); auto metadata = csr->getCurrentMetadataIfKnown(); diff --git a/src/mongo/db/s/op_observer_sharding_test.cpp b/src/mongo/db/s/op_observer_sharding_test.cpp index 65754edcd71..644627a95b8 100644 --- a/src/mongo/db/s/op_observer_sharding_test.cpp +++ b/src/mongo/db/s/op_observer_sharding_test.cpp @@ -70,8 +70,9 @@ protected: auto db = databaseHolder->openDb(operationContext(), kTestNss.dbName(), &justCreated); auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireExclusive( operationContext(), kTestNss.dbName()); - scopedDss->setDbInfo(operationContext(), - DatabaseType{kTestNss.dbName().db(), ShardId("this"), dbVersion1}); + scopedDss->setDbInfo( + operationContext(), + DatabaseType{kTestNss.dbName().db().toString(), ShardId("this"), dbVersion1}); ASSERT_TRUE(db); ASSERT_TRUE(justCreated); diff --git a/src/mongo/db/s/query_analysis_writer.cpp b/src/mongo/db/s/query_analysis_writer.cpp index 668910cc2cb..59b3be0002f 100644 --- a/src/mongo/db/s/query_analysis_writer.cpp +++ b/src/mongo/db/s/query_analysis_writer.cpp @@ -81,7 +81,7 @@ BSONObj createIndex(OperationContext* opCtx, const NamespaceString& nss, const B DBDirectClient client(opCtx); client.runCommand( - nss.db(), + DatabaseName{nss.db()}, BSON("createIndexes" << nss.coll().toString() << "indexes" << BSON_ARRAY(indexSpec)), resObj); diff --git a/src/mongo/db/s/query_analysis_writer_test.cpp b/src/mongo/db/s/query_analysis_writer_test.cpp index d6046d5f3a5..a83a9d52c03 100644 --- a/src/mongo/db/s/query_analysis_writer_test.cpp +++ b/src/mongo/db/s/query_analysis_writer_test.cpp @@ -210,7 +210,8 @@ protected: void assertTTLIndexExists(const NamespaceString& nss, const std::string& name) const { DBDirectClient client(operationContext()); BSONObj result; - client.runCommand(nss.db(), BSON("listIndexes" << nss.coll().toString()), result); + client.runCommand( + DatabaseName{nss.db()}, BSON("listIndexes" << nss.coll().toString()), result); auto indexes = result.getObjectField("cursor").getField("firstBatch").Array(); auto iter = indexes.begin(); diff --git a/src/mongo/db/s/range_deletion_util.cpp b/src/mongo/db/s/range_deletion_util.cpp index 48d606806e8..fde7c227f23 100644 --- a/src/mongo/db/s/range_deletion_util.cpp +++ b/src/mongo/db/s/range_deletion_util.cpp @@ -132,7 +132,7 @@ StatusWith deleteNextBatch(OperationContext* opCtx, if (serverGlobalParams.moveParanoia) { deleteStageParams->removeSaver = - std::make_unique("moveChunk", nss.ns(), "cleaning"); + std::make_unique("moveChunk", nss.ns().toString(), "cleaning"); } auto exec = @@ -261,9 +261,10 @@ ExecutorFuture deleteRangeInBatchesWithExecutor( return ExecutorFuture(executor).then([=] { return withTemporaryOperationContext( [=](OperationContext* opCtx) { - return deleteRangeInBatches(opCtx, nss.db(), collectionUuid, keyPattern, range); + return deleteRangeInBatches( + opCtx, DatabaseName{nss.db()}, collectionUuid, keyPattern, range); }, - nss.db(), + DatabaseName{nss.db()}, collectionUuid); }); } @@ -291,7 +292,7 @@ ExecutorFuture waitForDeletionsToMajorityReplicate( .waitUntilMajority(clientOpTime, CancellationToken::uncancelable()) .thenRunOn(executor); }, - nss.db(), + DatabaseName{nss.db()}, collectionUuid); } @@ -545,7 +546,7 @@ SharedSemiFuture removeDocumentsInRange( [&](OperationContext* opCtx) { removePersistentRangeDeletionTask(opCtx, collectionUuid, range); }, - nss.db(), + DatabaseName{nss.db()}, collectionUuid); } catch (const DBException& e) { LOGV2_ERROR(23770, diff --git a/src/mongo/db/s/rename_collection_coordinator.cpp b/src/mongo/db/s/rename_collection_coordinator.cpp index 8610f11aa14..38c63f3b14c 100644 --- a/src/mongo/db/s/rename_collection_coordinator.cpp +++ b/src/mongo/db/s/rename_collection_coordinator.cpp @@ -360,7 +360,7 @@ ExecutorFuture RenameCollectionCoordinator::_runImpl( // - Locally rename source to target ShardsvrRenameCollectionParticipant renameCollParticipantRequest( fromNss, _doc.getSourceUUID().value()); - renameCollParticipantRequest.setDbName(fromNss.db()); + renameCollParticipantRequest.setDbName(DatabaseName{fromNss.db()}); renameCollParticipantRequest.setTargetUUID(_doc.getTargetUUID()); renameCollParticipantRequest.setRenameCollectionRequest(_request); const auto cmdObj = CommandHelpers::appendMajorityWriteConcern( @@ -451,7 +451,7 @@ ExecutorFuture RenameCollectionCoordinator::_runImpl( // - Unblock CRUD on participants for both source and destination collections ShardsvrRenameCollectionUnblockParticipant unblockParticipantRequest( fromNss, _doc.getSourceUUID().value()); - unblockParticipantRequest.setDbName(fromNss.db()); + unblockParticipantRequest.setDbName(DatabaseName{fromNss.db()}); unblockParticipantRequest.setRenameCollectionRequest(_request); auto const cmdObj = CommandHelpers::appendMajorityWriteConcern( unblockParticipantRequest.toBSON({})); diff --git a/src/mongo/db/s/reshard_collection_coordinator.cpp b/src/mongo/db/s/reshard_collection_coordinator.cpp index 8f59b884955..064789b14f3 100644 --- a/src/mongo/db/s/reshard_collection_coordinator.cpp +++ b/src/mongo/db/s/reshard_collection_coordinator.cpp @@ -159,7 +159,7 @@ ExecutorFuture ReshardCollectionCoordinator::_runImpl( _updateStateDocument(opCtx, std::move(newDoc)); ConfigsvrReshardCollection configsvrReshardCollection(nss(), _doc.getKey()); - configsvrReshardCollection.setDbName(nss().db()); + configsvrReshardCollection.setDbName(DatabaseName{nss().db()}); configsvrReshardCollection.setUnique(_doc.getUnique()); configsvrReshardCollection.setCollation(_doc.getCollation()); configsvrReshardCollection.set_presetReshardedChunks( diff --git a/src/mongo/db/s/resharding/resharding_coordinator_commit_monitor.cpp b/src/mongo/db/s/resharding/resharding_coordinator_commit_monitor.cpp index 6cc7f93abad..68f640d13b6 100644 --- a/src/mongo/db/s/resharding/resharding_coordinator_commit_monitor.cpp +++ b/src/mongo/db/s/resharding/resharding_coordinator_commit_monitor.cpp @@ -61,7 +61,7 @@ MONGO_FAIL_POINT_DEFINE(hangBeforeQueryingRecipients); BSONObj makeCommandObj(const NamespaceString& ns) { auto command = _shardsvrReshardingOperationTime(ns); - command.setDbName(DatabaseName(ns.tenantId(), "admin")); + command.setDbName(DatabaseName(ns.tenantId(), DatabaseName::kAdmin.db())); return command.toBSON({}); } diff --git a/src/mongo/db/s/resharding/resharding_coordinator_service.cpp b/src/mongo/db/s/resharding/resharding_coordinator_service.cpp index 2358d4b00a6..75b1b591fff 100644 --- a/src/mongo/db/s/resharding/resharding_coordinator_service.cpp +++ b/src/mongo/db/s/resharding/resharding_coordinator_service.cpp @@ -697,7 +697,7 @@ void executeMetadataChangesInTxn( BSONObj makeFlushRoutingTableCacheUpdatesCmd(const NamespaceString& nss) { auto cmd = FlushRoutingTableCacheUpdatesWithWriteConcern(nss); cmd.setSyncFromConfig(true); - cmd.setDbName(nss.db()); + cmd.setDbName(DatabaseName{nss.db()}); return cmd.toBSON( BSON(WriteConcernOptions::kWriteConcernField << kMajorityWriteConcern.toBSON())); } @@ -789,7 +789,8 @@ void writeDecisionPersistedState(OperationContext* opCtx, txnNumber); // Delete all of the config.tags entries for the user collection namespace. - const auto removeTagsQuery = BSON(TagsType::ns(coordinatorDoc.getSourceNss().ns())); + const auto removeTagsQuery = + BSON(TagsType::ns(coordinatorDoc.getSourceNss().ns().toString())); removeTagsDocs(opCtx, removeTagsQuery); // Update all of the config.tags entries for the temporary resharding namespace @@ -803,11 +804,11 @@ void updateTagsDocsForTempNss(OperationContext* opCtx, auto hint = BSON("ns" << 1 << "min" << 1); auto tagsRequest = BatchedCommandRequest::buildUpdateOp( TagsType::ConfigNS, - BSON(TagsType::ns(coordinatorDoc.getTempReshardingNss().ns())), // query - BSON("$set" << BSON("ns" << coordinatorDoc.getSourceNss().ns())), // update - false, // upsert - true, // multi - hint // hint + BSON(TagsType::ns(coordinatorDoc.getTempReshardingNss().ns().toString())), // query + BSON("$set" << BSON("ns" << coordinatorDoc.getSourceNss().ns())), // update + false, // upsert + true, // multi + hint // hint ); // Update the 'ns' field to be the original collection namespace for all tags documents that @@ -861,7 +862,8 @@ void writeParticipantShardsAndTempCollInfo( std::vector initialChunks, std::vector zones, boost::optional indexVersion) { - const auto tagsQuery = BSON(TagsType::ns(updatedCoordinatorDoc.getTempReshardingNss().ns())); + const auto tagsQuery = + BSON(TagsType::ns(updatedCoordinatorDoc.getTempReshardingNss().ns().toString())); removeChunkAndTagsDocs(opCtx, tagsQuery, updatedCoordinatorDoc.getReshardingUUID()); insertChunkAndTagDocsForTempNss(opCtx, initialChunks, zones); @@ -944,7 +946,8 @@ void removeCoordinatorDocAndReshardingFields(OperationContext* opCtx, updatedCoordinatorDoc.setState(CoordinatorStateEnum::kDone); emplaceTruncatedAbortReasonIfExists(updatedCoordinatorDoc, abortReason); - const auto tagsQuery = BSON(TagsType::ns(coordinatorDoc.getTempReshardingNss().ns())); + const auto tagsQuery = + BSON(TagsType::ns(coordinatorDoc.getTempReshardingNss().ns().toString())); // Once the decision has been persisted, the coordinator would have modified the // config.chunks and config.collections entry. This means that the UUID of the // non-temp collection is now the UUID of what was previously the UUID of the temp diff --git a/src/mongo/db/s/resharding/resharding_manual_cleanup.cpp b/src/mongo/db/s/resharding/resharding_manual_cleanup.cpp index fad84d1a4e8..8e0caf72733 100644 --- a/src/mongo/db/s/resharding/resharding_manual_cleanup.cpp +++ b/src/mongo/db/s/resharding/resharding_manual_cleanup.cpp @@ -239,7 +239,7 @@ bool ReshardingCoordinatorCleaner::_checkExistsTempReshardingCollection( void ReshardingCoordinatorCleaner::_dropTemporaryReshardingCollection( OperationContext* opCtx, const NamespaceString& tempReshardingNss) { ShardsvrDropCollection dropCollectionCommand(tempReshardingNss); - dropCollectionCommand.setDbName(tempReshardingNss.db()); + dropCollectionCommand.setDbName(DatabaseName{tempReshardingNss.db()}); const auto dbInfo = uassertStatusOK( Grid::get(opCtx)->catalogCache()->getDatabase(opCtx, tempReshardingNss.db())); diff --git a/src/mongo/db/s/sessions_collection_config_server.cpp b/src/mongo/db/s/sessions_collection_config_server.cpp index 8aa967d33cb..86ad7cfe44c 100644 --- a/src/mongo/db/s/sessions_collection_config_server.cpp +++ b/src/mongo/db/s/sessions_collection_config_server.cpp @@ -64,7 +64,7 @@ void SessionsCollectionConfigServer::_shardCollectionIfNeeded(OperationContext* CreateCollectionRequest requestParamsObj; requestParamsObj.setShardKey(BSON("_id" << 1)); shardsvrCollRequest.setCreateCollectionRequest(std::move(requestParamsObj)); - shardsvrCollRequest.setDbName(NamespaceString::kLogicalSessionsNamespace.db()); + shardsvrCollRequest.setDbName(DatabaseName{NamespaceString::kLogicalSessionsNamespace.db()}); cluster::createCollection(opCtx, shardsvrCollRequest); } diff --git a/src/mongo/db/s/shard_filtering_metadata_refresh.cpp b/src/mongo/db/s/shard_filtering_metadata_refresh.cpp index 17474c445dd..ecc4832caa3 100644 --- a/src/mongo/db/s/shard_filtering_metadata_refresh.cpp +++ b/src/mongo/db/s/shard_filtering_metadata_refresh.cpp @@ -241,11 +241,12 @@ void onDbVersionMismatch(OperationContext* opCtx, { boost::optional dbLock; - dbLock.emplace(opCtx, dbName, MODE_IS); + dbLock.emplace(opCtx, DatabaseName{dbName}, MODE_IS); if (receivedDbVersion) { - auto scopedDss = boost::make_optional( - DatabaseShardingState::assertDbLockedAndAcquireShared(opCtx, dbName)); + auto scopedDss = + boost::make_optional(DatabaseShardingState::assertDbLockedAndAcquireShared( + opCtx, DatabaseName{dbName})); if (joinDbVersionOperation(opCtx, &dbLock, &scopedDss)) { // Waited for another thread to exit from the critical section or to complete an @@ -270,8 +271,9 @@ void onDbVersionMismatch(OperationContext* opCtx, return; } - auto scopedDss = boost::make_optional( - DatabaseShardingState::assertDbLockedAndAcquireExclusive(opCtx, dbName)); + auto scopedDss = + boost::make_optional(DatabaseShardingState::assertDbLockedAndAcquireExclusive( + opCtx, DatabaseName{dbName})); if (joinDbVersionOperation(opCtx, &dbLock, &scopedDss)) { // Waited for another thread to exit from the critical section or to complete an @@ -288,7 +290,7 @@ void onDbVersionMismatch(OperationContext* opCtx, CancellationToken cancellationToken = cancellationSource.token(); (*scopedDss) ->setDbMetadataRefreshFuture( - recoverRefreshDbVersion(opCtx, dbName, cancellationToken), + recoverRefreshDbVersion(opCtx, DatabaseName{dbName}, cancellationToken), std::move(cancellationSource)); dbMetadataRefreshFuture = (*scopedDss)->getDbMetadataRefreshFuture(); } diff --git a/src/mongo/db/s/sharding_catalog_client_aggregations_test.cpp b/src/mongo/db/s/sharding_catalog_client_aggregations_test.cpp index 23d3a49da25..c3ae0750871 100644 --- a/src/mongo/db/s/sharding_catalog_client_aggregations_test.cpp +++ b/src/mongo/db/s/sharding_catalog_client_aggregations_test.cpp @@ -433,10 +433,12 @@ TEST_F(CatalogClientAggregationsTest, GetShardsThatOwnDataForCollAtClusterTime_W auto opCtx = operationContext(); PlacementDescriptor _startFcvMarker = { Timestamp(1, 0), - NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns(), + NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns().toString(), {"shard1", "shard2", "shard3", "shard4", "shard5"}}; PlacementDescriptor _endFcvMarker = { - Timestamp(3, 0), NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns(), {}}; + Timestamp(3, 0), + NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns().toString(), + {}}; // initialization setupConfigPlacementHistory( @@ -680,10 +682,12 @@ TEST_F(CatalogClientAggregationsTest, GetShardsThatOwnDataForDbAtClusterTime_Wit auto opCtx = operationContext(); PlacementDescriptor _startFcvMarker = { Timestamp(1, 0), - NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns(), + NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns().toString(), {"shard1", "shard2", "shard3", "shard4", "shard5"}}; PlacementDescriptor _endFcvMarker = { - Timestamp(3, 0), NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns(), {}}; + Timestamp(3, 0), + NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns().toString(), + {}}; // initialization setupConfigPlacementHistory( @@ -889,10 +893,12 @@ TEST_F(CatalogClientAggregationsTest, GetShardsThatOwnDataAtClusterTime_WithMark auto opCtx = operationContext(); PlacementDescriptor _startFcvMarker = { Timestamp(1, 0), - NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns(), + NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns().toString(), {"shard1", "shard2", "shard3", "shard4"}}; PlacementDescriptor _endFcvMarker = { - Timestamp(3, 0), NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns(), {}}; + Timestamp(3, 0), + NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns().toString(), + {}}; // initialization setupConfigPlacementHistory( @@ -1194,10 +1200,12 @@ TEST_F(CatalogClientAggregationsTest, GetShardsThatOwnDataAtClusterTime_CleanUp_ auto opCtx = operationContext(); PlacementDescriptor startFcvMarker = { Timestamp(1, 0), - NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns(), + NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns().toString(), {"shard1", "shard2", "shard3", "shard4"}}; PlacementDescriptor endFcvMarker = { - Timestamp(3, 0), NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns(), {}}; + Timestamp(3, 0), + NamespaceString::kConfigsvrPlacementHistoryFcvMarkerNamespace.ns().toString(), + {}}; // initialization setupConfigPlacementHistory( diff --git a/src/mongo/db/s/sharding_ddl_coordinator.cpp b/src/mongo/db/s/sharding_ddl_coordinator.cpp index 0606cba0993..dc746339fbf 100644 --- a/src/mongo/db/s/sharding_ddl_coordinator.cpp +++ b/src/mongo/db/s/sharding_ddl_coordinator.cpp @@ -289,7 +289,8 @@ SemiFuture ShardingDDLCoordinator::run(std::shared_ptr autoGetDb; - autoGetDb.emplace(opCtx, NamespaceString::kServerConfigurationNamespace.db(), MODE_X); + autoGetDb.emplace( + opCtx, DatabaseName{NamespaceString::kServerConfigurationNamespace.db()}, MODE_X); const auto configOpTime = [&]() { const auto vcTime = VectorClock::get(opCtx)->getTime(); diff --git a/src/mongo/db/s/sharding_util.cpp b/src/mongo/db/s/sharding_util.cpp index 4cf80f20341..395e1bd463c 100644 --- a/src/mongo/db/s/sharding_util.cpp +++ b/src/mongo/db/s/sharding_util.cpp @@ -58,7 +58,7 @@ void tellShardsToRefreshCollection(OperationContext* opCtx, const std::shared_ptr& executor) { auto cmd = FlushRoutingTableCacheUpdatesWithWriteConcern(nss); cmd.setSyncFromConfig(true); - cmd.setDbName(nss.db()); + cmd.setDbName(DatabaseName{nss.db()}); auto cmdObj = CommandHelpers::appendMajorityWriteConcern(cmd.toBSON({})); sendCommandToShards(opCtx, DatabaseName::kAdmin.db(), cmdObj, shardIds, executor); } diff --git a/src/mongo/db/s/shardsvr_check_metadata_consistency_command.cpp b/src/mongo/db/s/shardsvr_check_metadata_consistency_command.cpp index cb96382be0f..673a7368bc7 100644 --- a/src/mongo/db/s/shardsvr_check_metadata_consistency_command.cpp +++ b/src/mongo/db/s/shardsvr_check_metadata_consistency_command.cpp @@ -202,7 +202,7 @@ public: const auto dbDDLLock = ddlLockManager->lock( opCtx, nss.db(), kLockReason, DDLLockManager::kDefaultLockTimeout); - DatabaseShardingState::assertIsPrimaryShardForDb(opCtx, nss.dbName()); + DatabaseShardingState::assertIsPrimaryShardForDb(opCtx, DatabaseName{nss.db()}); return establishCursors(opCtx, Grid::get(opCtx)->getExecutorPool()->getFixedExecutor(), diff --git a/src/mongo/db/s/shardsvr_drop_indexes_command.cpp b/src/mongo/db/s/shardsvr_drop_indexes_command.cpp index 0a552d680a0..237ab96fa0f 100644 --- a/src/mongo/db/s/shardsvr_drop_indexes_command.cpp +++ b/src/mongo/db/s/shardsvr_drop_indexes_command.cpp @@ -160,7 +160,7 @@ ShardsvrDropIndexesCommand::Invocation::Response ShardsvrDropIndexesCommand::Inv auto dbDDLLock = ddlLockManager->lock(opCtx, ns().db(), lockReason, lockTimeout); // Check under the dbLock if this is still the primary shard for the database - DatabaseShardingState::assertIsPrimaryShardForDb(opCtx, ns().db()); + DatabaseShardingState::assertIsPrimaryShardForDb(opCtx, DatabaseName{ns().db()}); auto resolvedNs = ns(); auto dropIdxBSON = dropIdxCmd.toBSON({}); diff --git a/src/mongo/db/service_entry_point_common.cpp b/src/mongo/db/service_entry_point_common.cpp index 3d5e515301f..3fea51ec200 100644 --- a/src/mongo/db/service_entry_point_common.cpp +++ b/src/mongo/db/service_entry_point_common.cpp @@ -1270,7 +1270,7 @@ void RunCommandImpl::_epilogue() { _ecd->getLastOpBeforeRun(), _ecd->getLastOpAfterRun()); appendAdditionalParticipants( - opCtx, &body, command->getName(), _ecd->getInvocation()->ns().ns()); + opCtx, &body, command->getName(), _ecd->getInvocation()->ns().ns().toString()); } auto commandBodyBob = replyBuilder->getBodyBuilder(); @@ -1945,7 +1945,7 @@ void ExecCommandDatabase::_handleFailure(Status status) { getLastOpBeforeRun(), getLastOpAfterRun()); appendAdditionalParticipants( - opCtx, &_extraFieldsBuilder, command->getName(), _execContext->nsString().ns()); + opCtx, &_extraFieldsBuilder, command->getName(), _execContext->nsString().ns().toString()); BSONObjBuilder metadataBob; behaviors.appendReplyMetadata(opCtx, request, &metadataBob); diff --git a/src/mongo/db/shard_role.cpp b/src/mongo/db/shard_role.cpp index 6bdefaf59ae..88933f3bff9 100644 --- a/src/mongo/db/shard_role.cpp +++ b/src/mongo/db/shard_role.cpp @@ -204,7 +204,8 @@ void checkPlacementVersion(OperationContext* opCtx, const PlacementConcern& placementConcern) { const auto& receivedDbVersion = placementConcern.dbVersion; if (receivedDbVersion) { - DatabaseShardingState::assertMatchingDbVersion(opCtx, nss.db(), *receivedDbVersion); + DatabaseShardingState::assertMatchingDbVersion( + opCtx, DatabaseName{nss.db()}, *receivedDbVersion); } const auto& receivedShardVersion = placementConcern.shardVersion; diff --git a/src/mongo/db/shard_role_test.cpp b/src/mongo/db/shard_role_test.cpp index 6c0993dae23..f630827261c 100644 --- a/src/mongo/db/shard_role_test.cpp +++ b/src/mongo/db/shard_role_test.cpp @@ -64,7 +64,7 @@ void installDatabaseMetadata(OperationContext* opCtx, const DatabaseVersion& dbVersion) { AutoGetDb autoDb(opCtx, dbName, MODE_X, {}, {}); auto scopedDss = DatabaseShardingState::assertDbLockedAndAcquireExclusive(opCtx, dbName); - scopedDss->setDbInfo(opCtx, {dbName.db(), ShardId("this"), dbVersion}); + scopedDss->setDbInfo(opCtx, {dbName.db().toString(), ShardId("this"), dbVersion}); } void installUnshardedCollectionMetadata(OperationContext* opCtx, const NamespaceString& nss) { @@ -838,18 +838,18 @@ TEST_F(ShardRoleTest, YieldAndRestoreAcquisitionWithLocks) { }, MODE_IX); - ASSERT_TRUE(opCtx()->lockState()->isDbLockedForMode(nss.db(), MODE_IX)); + ASSERT_TRUE(opCtx()->lockState()->isDbLockedForMode(DatabaseName{nss.db()}, MODE_IX)); ASSERT_TRUE(opCtx()->lockState()->isCollectionLockedForMode(nss, MODE_IX)); // Yield the resources auto yieldedTransactionResources = yieldTransactionResourcesFromOperationContext(opCtx()); ASSERT(yieldedTransactionResources); - ASSERT_FALSE(opCtx()->lockState()->isDbLockedForMode(nss.db(), MODE_IX)); + ASSERT_FALSE(opCtx()->lockState()->isDbLockedForMode(DatabaseName{nss.db()}, MODE_IX)); ASSERT_FALSE(opCtx()->lockState()->isCollectionLockedForMode(nss, MODE_IX)); // Restore the resources restoreTransactionResourcesToOperationContext(opCtx(), std::move(*yieldedTransactionResources)); - ASSERT_TRUE(opCtx()->lockState()->isDbLockedForMode(nss.db(), MODE_IX)); + ASSERT_TRUE(opCtx()->lockState()->isDbLockedForMode(DatabaseName{nss.db()}, MODE_IX)); ASSERT_TRUE(opCtx()->lockState()->isCollectionLockedForMode(nss, MODE_IX)); } @@ -898,7 +898,7 @@ TEST_F(ShardRoleTest, RestoreForWriteFailsIfPlacementConcernNoLongerMet) { ASSERT_FALSE(exInfo->getCriticalSectionSignal().is_initialized()); }); - ASSERT_FALSE(opCtx()->lockState()->isDbLockedForMode(nss.db(), MODE_IX)); + ASSERT_FALSE(opCtx()->lockState()->isDbLockedForMode(DatabaseName{nss.db()}, MODE_IX)); ASSERT_FALSE(opCtx()->lockState()->isCollectionLockedForMode(nss, MODE_IX)); } diff --git a/src/mongo/db/stats/fill_locker_info_test.cpp b/src/mongo/db/stats/fill_locker_info_test.cpp index 3bc23346349..2ab5714f6e3 100644 --- a/src/mongo/db/stats/fill_locker_info_test.cpp +++ b/src/mongo/db/stats/fill_locker_info_test.cpp @@ -92,7 +92,7 @@ DEATH_TEST(FillLockerInfo, ShouldFailIfLocksAreNotSortedAppropriately, "Invarian } TEST(FillLockerInfo, DoesReportLocksHeld) { - const ResourceId dbId(RESOURCE_DATABASE, "TestDB"_sd); + const ResourceId dbId(RESOURCE_DATABASE, DatabaseName{"TestDB"_sd}); LockerInfo info; info.locks = {OneLock{resourceIdGlobal, MODE_IX}, OneLock{dbId, MODE_IX}}; @@ -109,8 +109,8 @@ TEST(FillLockerInfo, DoesReportLocksHeld) { } TEST(FillLockerInfo, ShouldReportMaxTypeHeldForResourceType) { - const ResourceId firstDbId(RESOURCE_DATABASE, "FirstDB"_sd); - const ResourceId secondDbId(RESOURCE_DATABASE, "SecondDB"_sd); + const ResourceId firstDbId(RESOURCE_DATABASE, DatabaseName{"FirstDB"_sd}); + const ResourceId secondDbId(RESOURCE_DATABASE, DatabaseName{"SecondDB"_sd}); LockerInfo info; info.locks = {OneLock{resourceIdGlobal, MODE_IX}, OneLock{firstDbId, MODE_IX}, diff --git a/src/mongo/db/storage/wiredtiger/wiredtiger_record_store.cpp b/src/mongo/db/storage/wiredtiger/wiredtiger_record_store.cpp index a47fa2aecb1..a7f6ec63ffc 100644 --- a/src/mongo/db/storage/wiredtiger/wiredtiger_record_store.cpp +++ b/src/mongo/db/storage/wiredtiger/wiredtiger_record_store.cpp @@ -600,7 +600,7 @@ std::string WiredTigerRecordStore::ns(OperationContext* opCtx) const { if (!nss) return ""; - return nss->ns(); + return nss->ns().toString(); } void WiredTigerRecordStore::checkSize(OperationContext* opCtx) { diff --git a/src/mongo/db/storage/wiredtiger/wiredtiger_record_store_test_harness.cpp b/src/mongo/db/storage/wiredtiger/wiredtiger_record_store_test_harness.cpp index 742c43b6262..db643dc6f13 100644 --- a/src/mongo/db/storage/wiredtiger/wiredtiger_record_store_test_harness.cpp +++ b/src/mongo/db/storage/wiredtiger/wiredtiger_record_store_test_harness.cpp @@ -116,7 +116,7 @@ std::unique_ptr WiredTigerHarnessHelper::newOplogRecordStore() { std::unique_ptr WiredTigerHarnessHelper::newOplogRecordStoreNoInit() { ServiceContext::UniqueOperationContext opCtx(newOperationContext()); WiredTigerRecoveryUnit* ru = checked_cast(opCtx->recoveryUnit()); - std::string ident = NamespaceString::kRsOplogNamespace.ns(); + std::string ident = NamespaceString::kRsOplogNamespace.ns().toString(); std::string uri = WiredTigerKVEngine::kTableUriPrefix + ident; CollectionOptions options; diff --git a/src/mongo/db/ttl.cpp b/src/mongo/db/ttl.cpp index 98e7d5fe662..c14bd33b50b 100644 --- a/src/mongo/db/ttl.cpp +++ b/src/mongo/db/ttl.cpp @@ -898,8 +898,8 @@ void TTLMonitor::onStepUp(OperationContext* opCtx) { // processCollModCommand() will acquire MODE_X access to the collection. BSONObjBuilder builder; - uassertStatusOK( - processCollModCommand(opCtx, {nss->db(), uuid}, collModCmd, &builder)); + uassertStatusOK(processCollModCommand( + opCtx, {DatabaseName{nss->db()}, uuid}, collModCmd, &builder)); auto result = builder.obj(); LOGV2( 6847701, diff --git a/src/mongo/db/views/view_catalog_test.cpp b/src/mongo/db/views/view_catalog_test.cpp index 1b1232dba64..967e0dc98cd 100644 --- a/src/mongo/db/views/view_catalog_test.cpp +++ b/src/mongo/db/views/view_catalog_test.cpp @@ -584,7 +584,7 @@ TEST_F(ViewCatalogFixture, LookupRIDAfterDropRollback) { ASSERT_OK(createView(operationContext(), viewName, viewOn, emptyPipeline, emptyCollation)); wunit.commit(); ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID).value(), - viewName.ns()); + viewName.ns().toString()); } { @@ -600,7 +600,7 @@ TEST_F(ViewCatalogFixture, LookupRIDAfterDropRollback) { // Do not commit, rollback. } // Make sure drop was rolled back and view is still in catalog. - ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), viewName.ns()); + ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), viewName.ns().toString()); } TEST_F(ViewCatalogFixture, LookupRIDAfterModify) { @@ -612,7 +612,7 @@ TEST_F(ViewCatalogFixture, LookupRIDAfterModify) { NamespaceString::createNamespaceString_forTest(boost::none, "db.view")); ASSERT_OK(createView(operationContext(), viewName, viewOn, emptyPipeline, emptyCollation)); ASSERT_OK(modifyView(operationContext(), viewName, viewOn, emptyPipeline)); - ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), viewName.ns()); + ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), viewName.ns().toString()); } TEST_F(ViewCatalogFixture, LookupRIDAfterModifyRollback) { @@ -626,7 +626,8 @@ TEST_F(ViewCatalogFixture, LookupRIDAfterModifyRollback) { WriteUnitOfWork wunit(operationContext()); ASSERT_OK(createView(operationContext(), viewName, viewOn, emptyPipeline, emptyCollation)); wunit.commit(); - ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), viewName.ns()); + ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), + viewName.ns().toString()); } { @@ -643,11 +644,12 @@ TEST_F(ViewCatalogFixture, LookupRIDAfterModifyRollback) { viewOn, emptyPipeline, view_catalog_helpers::validatePipeline)); - ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), viewName.ns()); + ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), + viewName.ns().toString()); // Do not commit, rollback. } // Make sure view resource is still available after rollback. - ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), viewName.ns()); + ASSERT_EQ(ResourceCatalog::get(getServiceContext()).name(resourceID), viewName.ns().toString()); } TEST_F(ViewCatalogFixture, CreateViewThenDropAndLookup) { diff --git a/src/mongo/db/views/view_definition_test.cpp b/src/mongo/db/views/view_definition_test.cpp index e6f71d33efe..19010030237 100644 --- a/src/mongo/db/views/view_definition_test.cpp +++ b/src/mongo/db/views/view_definition_test.cpp @@ -118,7 +118,8 @@ TEST(ViewDefinitionTest, SetViewOnSucceedsIfNewViewOnIsInSameDatabaseAsView) { } TEST(ViewDefinitionTest, SetPipelineSucceedsOnValidArrayBSONElement) { - ViewDefinition viewDef(viewNss.db(), viewNss.coll(), backingNss.coll(), BSONObj(), nullptr); + ViewDefinition viewDef( + DatabaseName{viewNss.db()}, viewNss.coll(), backingNss.coll(), BSONObj(), nullptr); ASSERT(viewDef.pipeline().empty()); BSONObj matchStage = BSON("match" << BSON("x" << 9)); diff --git a/src/mongo/dbtests/clienttests.cpp b/src/mongo/dbtests/clienttests.cpp index 262a0010a5a..c65ddc2885a 100644 --- a/src/mongo/dbtests/clienttests.cpp +++ b/src/mongo/dbtests/clienttests.cpp @@ -66,8 +66,8 @@ public: return _nss; } - const std::string& ns() { - return _nss.toString(); + StringData ns() { + return _nss.ns(); } const NamespaceString _nss; diff --git a/src/mongo/dbtests/dbtests.cpp b/src/mongo/dbtests/dbtests.cpp index 97ae6f11d6d..f232e1e1274 100644 --- a/src/mongo/dbtests/dbtests.cpp +++ b/src/mongo/dbtests/dbtests.cpp @@ -181,7 +181,7 @@ Status createIndexFromSpec(OperationContext* opCtx, StringData ns, const BSONObj WriteContextForTests::WriteContextForTests(OperationContext* opCtx, StringData ns) : _opCtx(opCtx), _nss(ns) { // Lock the database and collection - _autoDb.emplace(opCtx, _nss.db(), MODE_IX); + _autoDb.emplace(opCtx, DatabaseName{_nss.db()}, MODE_IX); _collLock.emplace(opCtx, _nss, MODE_IX); const bool doShardVersionCheck = false; diff --git a/src/mongo/dbtests/mock/mock_remote_db_server.cpp b/src/mongo/dbtests/mock/mock_remote_db_server.cpp index 9c6e880edee..5ad274084d6 100644 --- a/src/mongo/dbtests/mock/mock_remote_db_server.cpp +++ b/src/mongo/dbtests/mock/mock_remote_db_server.cpp @@ -127,22 +127,23 @@ void MockRemoteDBServer::setCommandReply(const string& cmdName, void MockRemoteDBServer::insert(const NamespaceString& nss, BSONObj obj) { scoped_spinlock sLock(_lock); - vector& mockCollection = _dataMgr[nss.ns()]; + vector& mockCollection = _dataMgr[nss.ns().toString()]; mockCollection.push_back(obj.copy()); } void MockRemoteDBServer::remove(const NamespaceString& nss, const BSONObj&) { scoped_spinlock sLock(_lock); - if (_dataMgr.count(nss.ns()) == 0) { + auto ns = nss.ns().toString(); + if (_dataMgr.count(ns) == 0) { return; } - _dataMgr.erase(nss.ns()); + _dataMgr.erase(ns); } -void MockRemoteDBServer::assignCollectionUuid(const std::string& ns, const mongo::UUID& uuid) { +void MockRemoteDBServer::assignCollectionUuid(StringData ns, const mongo::UUID& uuid) { scoped_spinlock sLock(_lock); - _uuidToNs[uuid] = ns; + _uuidToNs[uuid] = ns.toString(); } rpc::UniqueReply MockRemoteDBServer::runCommand(InstanceID id, const OpMsgRequest& request) { @@ -213,7 +214,7 @@ mongo::BSONArray MockRemoteDBServer::findImpl(InstanceID id, scoped_spinlock sLock(_lock); _queryCount++; - auto ns = nsOrUuid.uuid() ? _uuidToNs[*nsOrUuid.uuid()] : nsOrUuid.nss()->ns(); + auto ns = nsOrUuid.uuid() ? _uuidToNs[*nsOrUuid.uuid()] : nsOrUuid.nss()->ns().toString(); const vector& coll = _dataMgr[ns]; BSONArrayBuilder result; for (vector::const_iterator iter = coll.begin(); iter != coll.end(); ++iter) { diff --git a/src/mongo/dbtests/mock/mock_remote_db_server.h b/src/mongo/dbtests/mock/mock_remote_db_server.h index 170d1617d6b..c3f7930b621 100644 --- a/src/mongo/dbtests/mock/mock_remote_db_server.h +++ b/src/mongo/dbtests/mock/mock_remote_db_server.h @@ -155,7 +155,7 @@ public: * @param ns the namespace to be associated with the uuid. * @param uuid the uuid to associate with the namespace. */ - void assignCollectionUuid(const std::string& ns, const mongo::UUID& uuid); + void assignCollectionUuid(StringData ns, const mongo::UUID& uuid); // // DBClientBase methods diff --git a/src/mongo/dbtests/plan_executor_invalidation_test.cpp b/src/mongo/dbtests/plan_executor_invalidation_test.cpp index 6c552e9e3a4..c84632abaab 100644 --- a/src/mongo/dbtests/plan_executor_invalidation_test.cpp +++ b/src/mongo/dbtests/plan_executor_invalidation_test.cpp @@ -129,7 +129,7 @@ public: return res; } - bool dropCollection(const std::string& ns) { + bool dropCollection(StringData ns) { bool res = _client.dropCollection(NamespaceString(ns)); _refreshCollection(); return res; diff --git a/src/mongo/dbtests/query_stage_and.cpp b/src/mongo/dbtests/query_stage_and.cpp index ce7448a5f10..7dd0fe15bdf 100644 --- a/src/mongo/dbtests/query_stage_and.cpp +++ b/src/mongo/dbtests/query_stage_and.cpp @@ -149,8 +149,8 @@ public: return BSONObj(); } - const char* ns() { - return _nss.ns().c_str(); + StringData ns() { + return _nss.ns(); } const NamespaceString& nss() { return _nss; diff --git a/src/mongo/dbtests/querytests.cpp b/src/mongo/dbtests/querytests.cpp index 091357cf35d..3d358516a0c 100644 --- a/src/mongo/dbtests/querytests.cpp +++ b/src/mongo/dbtests/querytests.cpp @@ -53,7 +53,7 @@ namespace mongo { namespace { -void insertOplogDocument(OperationContext* opCtx, Timestamp ts, const char* ns) { +void insertOplogDocument(OperationContext* opCtx, Timestamp ts, StringData ns) { AutoGetCollection coll(opCtx, NamespaceString{ns}, MODE_IX); WriteUnitOfWork wuow(opCtx); auto doc = BSON("ts" << ts); @@ -730,7 +730,7 @@ public: << "oplog.querytests.OplogScanWithGtTimstampPred"), info); } - const char* ns = _nss.ns().c_str(); + const auto ns = _nss.ns(); insertOplogDocument(&_opCtx, Timestamp(1000, 0), ns); insertOplogDocument(&_opCtx, Timestamp(1000, 1), ns); insertOplogDocument(&_opCtx, Timestamp(1000, 2), ns); @@ -783,7 +783,7 @@ public: info); } - const char* ns = _nss.ns().c_str(); + const auto ns = _nss.ns(); insertOplogDocument(&_opCtx, Timestamp(1000, 0), ns); insertOplogDocument(&_opCtx, Timestamp(1000, 1), ns); insertOplogDocument(&_opCtx, Timestamp(1000, 2), ns); @@ -1347,8 +1347,8 @@ public: return CursorManager::get(&_opCtx)->numCursors(); } - const char* ns() { - return _nss.ns().c_str(); + StringData ns() { + return _nss.ns(); } const NamespaceString& nss() { return _nss; diff --git a/src/mongo/dbtests/rollbacktests.cpp b/src/mongo/dbtests/rollbacktests.cpp index 70aee1d3d1a..95667e062fb 100644 --- a/src/mongo/dbtests/rollbacktests.cpp +++ b/src/mongo/dbtests/rollbacktests.cpp @@ -57,7 +57,7 @@ void dropDatabase(OperationContext* opCtx, const NamespaceString& nss) { } } -bool collectionExists(OperationContext* opCtx, OldClientContext* ctx, const std::string& ns) { +bool collectionExists(OperationContext* opCtx, OldClientContext* ctx, StringData ns) { return (bool)CollectionCatalog::get(opCtx)->lookupCollectionByNamespace(opCtx, NamespaceString(ns)); } diff --git a/src/mongo/idl/idl_test.cpp b/src/mongo/idl/idl_test.cpp index c70ca8adb59..a00c1951796 100644 --- a/src/mongo/idl/idl_test.cpp +++ b/src/mongo/idl/idl_test.cpp @@ -2877,7 +2877,7 @@ TEST(IDLCommand, TestIgnore) { BasicIgnoredCommand one_new; one_new.setField1(3); one_new.setField2("five"); - one_new.setDbName(DatabaseName(boost::none, "admin")); + one_new.setDbName(DatabaseName::kAdmin); ASSERT_BSONOBJ_EQ(testDocWithDB, serializeCmd(one_new)); } } diff --git a/src/mongo/s/catalog/sharding_catalog_client_impl.cpp b/src/mongo/s/catalog/sharding_catalog_client_impl.cpp index cc7349c4cf7..fdb924af0e6 100644 --- a/src/mongo/s/catalog/sharding_catalog_client_impl.cpp +++ b/src/mongo/s/catalog/sharding_catalog_client_impl.cpp @@ -808,7 +808,7 @@ StatusWith> ShardingCatalogClientImpl::getTagsForCollectio kConfigReadSelector, repl::ReadConcernLevel::kMajorityReadConcern, TagsType::ConfigNS, - BSON(TagsType::ns(nss.ns())), + BSON(TagsType::ns(nss.ns().toString())), BSON(TagsType::min() << 1), boost::none); // no limit if (!findStatus.isOK()) { diff --git a/src/mongo/s/client/shard_remote.cpp b/src/mongo/s/client/shard_remote.cpp index 8f7e7443e23..e58cc7c6bca 100644 --- a/src/mongo/s/client/shard_remote.cpp +++ b/src/mongo/s/client/shard_remote.cpp @@ -506,7 +506,8 @@ StatusWith ShardRemote::_scheduleCommand( const auto readPrefWithConfigTime = [&]() -> ReadPreferenceSetting { // TODO SERVER-74281: Append this higher up when we know we're targeting the config to read // metadata or use a better filter to avoid matching logical sessions collection. - if (isConfig() && (dbName == DatabaseName::kConfig || dbName == DatabaseName::kAdmin)) { + if (isConfig() && + (dbName == DatabaseName::kConfig.db() || dbName == DatabaseName::kAdmin.db())) { const auto vcTime = VectorClock::get(opCtx)->getTime(); ReadPreferenceSetting readPrefToReturn{readPref}; readPrefToReturn.minClusterTime = vcTime.configTime().asTimestamp(); diff --git a/src/mongo/s/cluster_commands_helpers.cpp b/src/mongo/s/cluster_commands_helpers.cpp index 1619df5129f..3d431d45952 100644 --- a/src/mongo/s/cluster_commands_helpers.cpp +++ b/src/mongo/s/cluster_commands_helpers.cpp @@ -214,7 +214,7 @@ std::vector gatherResponsesImpl( MultiStatementTransactionRequestsSender ars( opCtx, Grid::get(opCtx)->getExecutorPool()->getArbitraryExecutor(), - dbName, + DatabaseName{dbName}, requests, readPref, retryPolicy); diff --git a/src/mongo/s/commands/cluster_count_cmd.h b/src/mongo/s/commands/cluster_count_cmd.h index 045b1895728..562957a67d1 100644 --- a/src/mongo/s/commands/cluster_count_cmd.h +++ b/src/mongo/s/commands/cluster_count_cmd.h @@ -229,7 +229,7 @@ public: return exceptionToStatus(); } - const NamespaceString nss(parseNs(request.getDatabase(), cmdObj)); + const NamespaceString nss = parseNs(DatabaseName{request.getDatabase()}, cmdObj); uassert(ErrorCodes::InvalidNamespace, str::stream() << "Invalid namespace specified '" << nss.ns() << "'", nss.isValid()); diff --git a/src/mongo/s/commands/cluster_distinct_cmd.cpp b/src/mongo/s/commands/cluster_distinct_cmd.cpp index 5fb9a701419..2cf1cdc9062 100644 --- a/src/mongo/s/commands/cluster_distinct_cmd.cpp +++ b/src/mongo/s/commands/cluster_distinct_cmd.cpp @@ -111,7 +111,7 @@ public: ExplainOptions::Verbosity verbosity, rpc::ReplyBuilderInterface* result) const override { const BSONObj& cmdObj = opMsgRequest.body; - const NamespaceString nss(parseNs(opMsgRequest.getDatabase(), cmdObj)); + const NamespaceString nss(parseNs(DatabaseName{opMsgRequest.getDatabase()}, cmdObj)); auto parsedDistinctCmd = ParsedDistinct::parse(opCtx, nss, cmdObj, ExtensionsCallbackNoop(), true); diff --git a/src/mongo/s/commands/cluster_drop_collection_cmd.cpp b/src/mongo/s/commands/cluster_drop_collection_cmd.cpp index efbfe0f26ac..38ab0dd6b2d 100644 --- a/src/mongo/s/commands/cluster_drop_collection_cmd.cpp +++ b/src/mongo/s/commands/cluster_drop_collection_cmd.cpp @@ -100,7 +100,7 @@ public: // Send it to the primary shard ShardsvrDropCollection dropCollectionCommand(nss); - dropCollectionCommand.setDbName(nss.db()); + dropCollectionCommand.setDbName(DatabaseName{nss.db()}); dropCollectionCommand.setCollectionUUID(request().getCollectionUUID()); auto cmdResponse = executeCommandAgainstDatabasePrimary( diff --git a/src/mongo/s/commands/cluster_move_primary_cmd.cpp b/src/mongo/s/commands/cluster_move_primary_cmd.cpp index e401f4811ea..72c5219ea42 100644 --- a/src/mongo/s/commands/cluster_move_primary_cmd.cpp +++ b/src/mongo/s/commands/cluster_move_primary_cmd.cpp @@ -96,7 +96,7 @@ public: const BSONObj& cmdObj, BSONObjBuilder& result) { auto request = MovePrimary::parse(IDLParserContext("MovePrimary"), cmdObj); - const string db = parseNs(dbName, cmdObj).dbName().db(); + const string db = parseNs(dbName, cmdObj).dbName().db().toString(); const StringData toShard(request.getTo()); // Invalidate the routing table cache entry for this database so that we reload the diff --git a/src/mongo/s/commands/cluster_rename_collection_cmd.cpp b/src/mongo/s/commands/cluster_rename_collection_cmd.cpp index 11c3de553c7..8bb453273b8 100644 --- a/src/mongo/s/commands/cluster_rename_collection_cmd.cpp +++ b/src/mongo/s/commands/cluster_rename_collection_cmd.cpp @@ -91,7 +91,7 @@ public: request().getDropTarget()); ShardsvrRenameCollection renameCollRequest(fromNss); - renameCollRequest.setDbName(fromNss.db()); + renameCollRequest.setDbName(DatabaseName{fromNss.db()}); renameCollRequest.setRenameCollectionRequest(renameCollReq); renameCollRequest.setAllowEncryptedCollectionRename( AuthorizationSession::get(opCtx->getClient()) diff --git a/src/mongo/s/commands/cluster_set_cluster_parameter_cmd.cpp b/src/mongo/s/commands/cluster_set_cluster_parameter_cmd.cpp index 3e26d8101e3..9cb643ff895 100644 --- a/src/mongo/s/commands/cluster_set_cluster_parameter_cmd.cpp +++ b/src/mongo/s/commands/cluster_set_cluster_parameter_cmd.cpp @@ -66,7 +66,7 @@ public: void typedRun(OperationContext* opCtx) { ConfigsvrSetClusterParameter configsvrSetClusterParameter( request().getCommandParameter()); - configsvrSetClusterParameter.setDbName(ns().db()); + configsvrSetClusterParameter.setDbName(DatabaseName{ns().db()}); const auto configShard = Grid::get(opCtx)->shardRegistry()->getConfigShard(); diff --git a/src/mongo/s/commands/cluster_set_feature_compatibility_version_cmd.cpp b/src/mongo/s/commands/cluster_set_feature_compatibility_version_cmd.cpp index 2f88401dc30..2a12e87911f 100644 --- a/src/mongo/s/commands/cluster_set_feature_compatibility_version_cmd.cpp +++ b/src/mongo/s/commands/cluster_set_feature_compatibility_version_cmd.cpp @@ -99,7 +99,7 @@ public: auto response = uassertStatusOK(configShard->runCommandWithFixedRetryAttempts( opCtx, ReadPreferenceSetting{ReadPreference::PrimaryOnly}, - cmd.getDbName().db(), + cmd.getDbName().db().toString(), CommandHelpers::appendMajorityWriteConcern(cmd.toBSON({}), opCtx->getWriteConcern()), Shard::RetryPolicy::kIdempotent)); diff --git a/src/mongo/s/commands/cluster_shard_collection_cmd.cpp b/src/mongo/s/commands/cluster_shard_collection_cmd.cpp index cab047e6ade..077a1c56a54 100644 --- a/src/mongo/s/commands/cluster_shard_collection_cmd.cpp +++ b/src/mongo/s/commands/cluster_shard_collection_cmd.cpp @@ -112,7 +112,7 @@ public: requestParamsObj.setImplicitlyCreateIndex(shardCollRequest.getImplicitlyCreateIndex()); requestParamsObj.setEnforceUniquenessCheck(shardCollRequest.getEnforceUniquenessCheck()); shardsvrCollRequest.setCreateCollectionRequest(std::move(requestParamsObj)); - shardsvrCollRequest.setDbName(nss.db()); + shardsvrCollRequest.setDbName(DatabaseName{nss.db()}); cluster::createCollection(opCtx, shardsvrCollRequest); diff --git a/src/mongo/s/commands/cluster_transition_to_catalog_shard_cmd.cpp b/src/mongo/s/commands/cluster_transition_to_catalog_shard_cmd.cpp index 10ed514dfdd..ea9ffaa6cf2 100644 --- a/src/mongo/s/commands/cluster_transition_to_catalog_shard_cmd.cpp +++ b/src/mongo/s/commands/cluster_transition_to_catalog_shard_cmd.cpp @@ -67,7 +67,7 @@ public: gFeatureFlagCatalogShard.isEnabled(serverGlobalParams.featureCompatibility)); ConfigsvrTransitionToCatalogShard cmdToSend; - cmdToSend.setDbName({"admin"}); + cmdToSend.setDbName(DatabaseName::kAdmin); auto configShard = Grid::get(opCtx)->shardRegistry()->getConfigShard(); diff --git a/src/mongo/s/commands/cluster_transition_to_dedicated_config_server_cmd.cpp b/src/mongo/s/commands/cluster_transition_to_dedicated_config_server_cmd.cpp index dc5001cf5b5..50f322ed1c9 100644 --- a/src/mongo/s/commands/cluster_transition_to_dedicated_config_server_cmd.cpp +++ b/src/mongo/s/commands/cluster_transition_to_dedicated_config_server_cmd.cpp @@ -90,7 +90,7 @@ public: auto configShard = Grid::get(opCtx)->shardRegistry()->getConfigShard(); ConfigsvrTransitionToDedicatedConfig transitionToDedicatedConfigServer; - transitionToDedicatedConfigServer.setDbName({"admin"}); + transitionToDedicatedConfigServer.setDbName(DatabaseName::kAdmin); // Force a reload of this node's shard list cache at the end of this command. auto cmdResponseWithStatus = configShard->runCommandWithFixedRetryAttempts( diff --git a/src/mongo/s/commands/internal_transactions_test_command.h b/src/mongo/s/commands/internal_transactions_test_command.h index ac1252beab9..083d4bc0a12 100644 --- a/src/mongo/s/commands/internal_transactions_test_command.h +++ b/src/mongo/s/commands/internal_transactions_test_command.h @@ -102,7 +102,7 @@ public: continue; } - const auto res = txnClient.runCommandSync(dbName, command); + const auto res = txnClient.runCommandSync(DatabaseName{dbName}, command); sharedBlock->responses.emplace_back( CommandHelpers::filterCommandReplyForPassthrough( diff --git a/src/mongo/s/query_analysis_client.cpp b/src/mongo/s/query_analysis_client.cpp index cd66f1beb7d..5651d403209 100644 --- a/src/mongo/s/query_analysis_client.cpp +++ b/src/mongo/s/query_analysis_client.cpp @@ -169,7 +169,7 @@ void QueryAnalysisClient::insert(OperationContext* opCtx, auto insertCmdObj = insertCmd.toBSON( {BSON(WriteConcernOptions::kWriteConcernField << kMajorityWriteConcern.toBSON())}); - executeCommandOnPrimary(opCtx, nss.db(), std::move(insertCmdObj), uassertCmdStatusFn); + executeCommandOnPrimary(opCtx, nss.dbName(), std::move(insertCmdObj), uassertCmdStatusFn); } } // namespace analyze_shard_key diff --git a/src/mongo/util/assert_util_core.h b/src/mongo/util/assert_util_core.h index 852ca464f17..61e4b8c1ca8 100644 --- a/src/mongo/util/assert_util_core.h +++ b/src/mongo/util/assert_util_core.h @@ -87,12 +87,9 @@ MONGO_COMPILER_NORETURN void invariantFailedWithMsg(const char* expr, // // Invariant failure !condition "hello!" some/file.cpp 528 // -#define MONGO_invariant_2(Expression, contextExpr) \ - ::mongo::invariantWithContextAndLocation((Expression), \ - #Expression, \ - [&]() -> std::string { return (contextExpr); }, \ - __FILE__, \ - __LINE__) +#define MONGO_invariant_2(Expression, contextExpr) \ + ::mongo::invariantWithContextAndLocation( \ + (Expression), #Expression, [&] { return std::string{contextExpr}; }, __FILE__, __LINE__) template inline void invariantWithContextAndLocation( -- cgit v1.2.1