From 85c5d57f8e84547e0add884e0de9b1266142b2f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Mon, 24 Feb 2025 22:28:10 +0100 Subject: [PATCH 1/2] PHPORM-278 Introduce Connection::getDatabase and getClient Deprecate getMongoDB and get MongoClient --- src/Concerns/ManagesTransactions.php | 11 ++++--- src/Connection.php | 42 ++++++++++++++++++++----- src/MongoDBServiceProvider.php | 6 ++-- src/Schema/Blueprint.php | 2 +- src/Schema/Builder.php | 14 ++++----- tests/ConnectionTest.php | 47 +++++++++++++++++++++++++--- 6 files changed, 95 insertions(+), 27 deletions(-) diff --git a/src/Concerns/ManagesTransactions.php b/src/Concerns/ManagesTransactions.php index ac3c1c6f7..6403cc45d 100644 --- a/src/Concerns/ManagesTransactions.php +++ b/src/Concerns/ManagesTransactions.php @@ -12,15 +12,18 @@ use function MongoDB\with_transaction; -/** @see https://docs.mongodb.com/manual/core/transactions/ */ +/** + * @internal + * + * @see https://docs.mongodb.com/manual/core/transactions/ + */ trait ManagesTransactions { protected ?Session $session = null; protected $transactions = 0; - /** @return Client */ - abstract public function getMongoClient(); + abstract public function getClient(): ?Client; public function getSession(): ?Session { @@ -30,7 +33,7 @@ public function getSession(): ?Session private function getSessionOrCreate(): Session { if ($this->session === null) { - $this->session = $this->getMongoClient()->startSession(); + $this->session = $this->getClient()->startSession(); } return $this->session; diff --git a/src/Connection.php b/src/Connection.php index 592e500e5..738955fa3 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -22,8 +22,11 @@ use function implode; use function is_array; use function preg_match; +use function sprintf; use function str_contains; +use function trigger_error; +use const E_USER_DEPRECATED; use const FILTER_FLAG_IPV6; use const FILTER_VALIDATE_IP; @@ -65,9 +68,10 @@ public function __construct(array $config) // Create the connection $this->connection = $this->createConnection($dsn, $config, $options); + $this->database = $this->getDefaultDatabaseName($dsn, $config); // Select database - $this->db = $this->connection->selectDatabase($this->getDefaultDatabaseName($dsn, $config)); + $this->db = $this->connection->selectDatabase($this->database); $this->tablePrefix = $config['prefix'] ?? ''; @@ -114,29 +118,53 @@ public function getSchemaBuilder() /** * Get the MongoDB database object. * + * @deprecated since mongodb/laravel-mongodb:5.2, use getDatabase() instead + * * @return Database */ public function getMongoDB() { + trigger_error(sprintf('Since mongodb/laravel-mongodb:5.2, Method "%s()" is deprecated, use "getDatabase()" instead.', __FUNCTION__), E_USER_DEPRECATED); + + return $this->db; + } + + /** + * Get the MongoDB database object. + * + * @param string|null $name Name of the database, if not provided the default database will be returned. + * + * @return Database + */ + public function getDatabase(?string $name = null): Database + { + if ($name && $name !== $this->database) { + return $this->connection->{$name}; + } + return $this->db; } /** - * return MongoDB object. + * Return MongoDB object. + * + * @deprecated since mongodb/laravel-mongodb:5.2, use getClient() instead * * @return Client */ public function getMongoClient() { - return $this->connection; + trigger_error(sprintf('Since mongodb/laravel-mongodb:5.2, method "%s()" is deprecated, use "getClient()" instead.', __FUNCTION__), E_USER_DEPRECATED); + + return $this->getClient(); } /** - * {@inheritDoc} + * Get the MongoDB client. */ - public function getDatabaseName() + public function getClient(): ?Client { - return $this->getMongoDB()->getDatabaseName(); + return $this->connection; } public function enableQueryLog() @@ -233,7 +261,7 @@ protected function createConnection(string $dsn, array $config, array $options): */ public function ping(): void { - $this->getMongoClient()->getManager()->selectServer(new ReadPreference(ReadPreference::PRIMARY_PREFERRED)); + $this->getClient()->getManager()->selectServer(new ReadPreference(ReadPreference::PRIMARY_PREFERRED)); } /** @inheritdoc */ diff --git a/src/MongoDBServiceProvider.php b/src/MongoDBServiceProvider.php index dc9caf082..f55540a8b 100644 --- a/src/MongoDBServiceProvider.php +++ b/src/MongoDBServiceProvider.php @@ -67,7 +67,7 @@ public function register() assert($connection instanceof Connection, new InvalidArgumentException(sprintf('The database connection "%s" used for the session does not use the "mongodb" driver.', $connectionName))); return new MongoDbSessionHandler( - $connection->getMongoClient(), + $connection->getClient(), $app->config->get('session.options', []) + [ 'database' => $connection->getDatabaseName(), 'collection' => $app->config->get('session.table') ?: 'sessions', @@ -132,7 +132,7 @@ private function registerFlysystemAdapter(): void throw new InvalidArgumentException(sprintf('The database connection "%s" does not use the "mongodb" driver.', $config['connection'] ?? $app['config']['database.default'])); } - $bucket = $connection->getMongoClient() + $bucket = $connection->getClient() ->selectDatabase($config['database'] ?? $connection->getDatabaseName()) ->selectGridFSBucket(['bucketName' => $config['bucket'] ?? 'fs', 'disableMD5' => true]); } @@ -171,7 +171,7 @@ private function registerScoutEngine(): void assert($connection instanceof Connection, new InvalidArgumentException(sprintf('The connection "%s" is not a MongoDB connection.', $connectionName))); - return new ScoutEngine($connection->getMongoDB(), $softDelete, $indexDefinitions); + return new ScoutEngine($connection->getDatabase(), $softDelete, $indexDefinitions); }); return $engineManager; diff --git a/src/Schema/Blueprint.php b/src/Schema/Blueprint.php index e3d7a230b..a525a9cee 100644 --- a/src/Schema/Blueprint.php +++ b/src/Schema/Blueprint.php @@ -251,7 +251,7 @@ public function create($options = []) { $collection = $this->collection->getCollectionName(); - $db = $this->connection->getMongoDB(); + $db = $this->connection->getDatabase(); // Ensure the collection is created. $db->createCollection($collection, $options); diff --git a/src/Schema/Builder.php b/src/Schema/Builder.php index fe806f0e5..4af15f1f9 100644 --- a/src/Schema/Builder.php +++ b/src/Schema/Builder.php @@ -76,7 +76,7 @@ public function hasColumns($table, array $columns): bool */ public function hasCollection($name) { - $db = $this->connection->getMongoDB(); + $db = $this->connection->getDatabase(); $collections = iterator_to_array($db->listCollections([ 'filter' => ['name' => $name], @@ -139,7 +139,7 @@ public function dropAllTables() public function getTables() { - $db = $this->connection->getMongoDB(); + $db = $this->connection->getDatabase(); $collections = []; foreach ($db->listCollectionNames() as $collectionName) { @@ -167,7 +167,7 @@ public function getTables() public function getTableListing() { - $collections = iterator_to_array($this->connection->getMongoDB()->listCollectionNames()); + $collections = iterator_to_array($this->connection->getDatabase()->listCollectionNames()); sort($collections); @@ -176,7 +176,7 @@ public function getTableListing() public function getColumns($table) { - $stats = $this->connection->getMongoDB()->selectCollection($table)->aggregate([ + $stats = $this->connection->getDatabase()->selectCollection($table)->aggregate([ // Sample 1,000 documents to get a representative sample of the collection ['$sample' => ['size' => 1_000]], // Convert each document to an array of fields @@ -229,7 +229,7 @@ public function getColumns($table) public function getIndexes($table) { - $collection = $this->connection->getMongoDB()->selectCollection($table); + $collection = $this->connection->getDatabase()->selectCollection($table); assert($collection instanceof Collection); $indexList = []; @@ -301,7 +301,7 @@ protected function createBlueprint($table, ?Closure $callback = null) */ public function getCollection($name) { - $db = $this->connection->getMongoDB(); + $db = $this->connection->getDatabase(); $collections = iterator_to_array($db->listCollections([ 'filter' => ['name' => $name], @@ -318,7 +318,7 @@ public function getCollection($name) protected function getAllCollections() { $collections = []; - foreach ($this->connection->getMongoDB()->listCollections() as $collection) { + foreach ($this->connection->getDatabase()->listCollections() as $collection) { $collections[] = $collection->getName(); } diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index 1efd17be0..ba5e09804 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -48,15 +48,15 @@ public function testDisconnectAndCreateNewConnection() { $connection = DB::connection('mongodb'); $this->assertInstanceOf(Connection::class, $connection); - $client = $connection->getMongoClient(); + $client = $connection->getClient(); $this->assertInstanceOf(Client::class, $client); $connection->disconnect(); - $client = $connection->getMongoClient(); + $client = $connection->getClient(); $this->assertNull($client); DB::purge('mongodb'); $connection = DB::connection('mongodb'); $this->assertInstanceOf(Connection::class, $connection); - $client = $connection->getMongoClient(); + $client = $connection->getClient(); $this->assertInstanceOf(Client::class, $client); } @@ -64,7 +64,7 @@ public function testDb() { $connection = DB::connection('mongodb'); $this->assertInstanceOf(Database::class, $connection->getMongoDB()); - $this->assertInstanceOf(Client::class, $connection->getMongoClient()); + $this->assertInstanceOf(Client::class, $connection->getClient()); } public static function dataConnectionConfig(): Generator @@ -196,7 +196,7 @@ public static function dataConnectionConfig(): Generator public function testConnectionConfig(string $expectedUri, string $expectedDatabaseName, array $config): void { $connection = new Connection($config); - $client = $connection->getMongoClient(); + $client = $connection->getClient(); $this->assertSame($expectedUri, (string) $client); $this->assertSame($expectedDatabaseName, $connection->getMongoDB()->getDatabaseName()); @@ -204,6 +204,43 @@ public function testConnectionConfig(string $expectedUri, string $expectedDataba $this->assertSame('foo', $connection->table('foo')->raw()->getCollectionName()); } + public function testLegacyGetMongoClient(): void + { + $connection = DB::connection('mongodb'); + $expected = $connection->getClient(); + + $this->assertSame($expected, $connection->getMongoClient()); + } + + public function testLegacyGetMongoDB(): void + { + $connection = DB::connection('mongodb'); + $expected = $connection->getDatabase(); + + $this->assertSame($expected, $connection->getMongoDB()); + } + + public function testGetDatabase(): void + { + $connection = DB::connection('mongodb'); + $defaultName = env('MONGODB_DATABASE', 'unittest'); + $database = $connection->getDatabase(); + + $this->assertInstanceOf(Database::class, $database); + $this->assertSame($defaultName, $database->getDatabaseName()); + $this->assertSame($database, $connection->getDatabase($defaultName), 'Same instance for the default database'); + } + + public function testGetOtherDatabase(): void + { + $connection = DB::connection('mongodb'); + $name = 'other_random_database'; + $database = $connection->getDatabase($name); + + $this->assertInstanceOf(Database::class, $database); + $this->assertSame($name, $database->getDatabaseName($name)); + } + public function testConnectionWithoutConfiguredDatabase(): void { $this->expectException(InvalidArgumentException::class); From bc796ce60cab0c02c36953d9ffd3b42b51c27ad4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Tue, 25 Feb 2025 16:33:19 +0100 Subject: [PATCH 2/2] Replace selectDatabase with getDatabase --- src/Connection.php | 4 ++-- src/MongoDBServiceProvider.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Connection.php b/src/Connection.php index 738955fa3..980750093 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -71,7 +71,7 @@ public function __construct(array $config) $this->database = $this->getDefaultDatabaseName($dsn, $config); // Select database - $this->db = $this->connection->selectDatabase($this->database); + $this->db = $this->connection->getDatabase($this->database); $this->tablePrefix = $config['prefix'] ?? ''; @@ -139,7 +139,7 @@ public function getMongoDB() public function getDatabase(?string $name = null): Database { if ($name && $name !== $this->database) { - return $this->connection->{$name}; + return $this->connection->getDatabase($name); } return $this->db; diff --git a/src/MongoDBServiceProvider.php b/src/MongoDBServiceProvider.php index f55540a8b..349abadc7 100644 --- a/src/MongoDBServiceProvider.php +++ b/src/MongoDBServiceProvider.php @@ -133,7 +133,7 @@ private function registerFlysystemAdapter(): void } $bucket = $connection->getClient() - ->selectDatabase($config['database'] ?? $connection->getDatabaseName()) + ->getDatabase($config['database'] ?? $connection->getDatabaseName()) ->selectGridFSBucket(['bucketName' => $config['bucket'] ?? 'fs', 'disableMD5' => true]); }