Skip to content

PHPORM-278 Introduce Connection::getDatabase() and getClient() #3289

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/Concerns/ManagesTransactions.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,18 @@

use function MongoDB\with_transaction;

/** @see https://docs.mongodb.com/manual/core/transactions/ */
/**
* @internal
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was this class always internal? Just curious if there's a BC concern here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We try to do better than Laravel's ManagesTransactions trait, that does not declare its dependencies. This trait is not meant to be used outside of the Connection class (it should be merged in it but we kept Laravel's design).

Technically, that's a breaking change that is easily overcome by adding a getClient method to the class that uses it.

*
* @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
{
Expand All @@ -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;
Expand Down
42 changes: 35 additions & 7 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this dynamically assigning a class property, or is this declared on BaseConnection?

Either way, this appears to be the first time it's being used.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The property is defined in the parent class, it was not set previously.


// Select database
$this->db = $this->connection->selectDatabase($this->getDefaultDatabaseName($dsn, $config));
$this->db = $this->connection->getDatabase($this->database);

$this->tablePrefix = $config['prefix'] ?? '';

Expand Down Expand Up @@ -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->getDatabase($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()
Expand Down Expand Up @@ -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 */
Expand Down
8 changes: 4 additions & 4 deletions src/MongoDBServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -132,8 +132,8 @@ 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()
->selectDatabase($config['database'] ?? $connection->getDatabaseName())
$bucket = $connection->getClient()
->getDatabase($config['database'] ?? $connection->getDatabaseName())
->selectGridFSBucket(['bucketName' => $config['bucket'] ?? 'fs', 'disableMD5' => true]);
}

Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/Schema/Blueprint.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
14 changes: 7 additions & 7 deletions src/Schema/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -139,7 +139,7 @@ public function dropAllTables()

public function getTables()
{
$db = $this->connection->getMongoDB();
$db = $this->connection->getDatabase();
$collections = [];

foreach ($db->listCollectionNames() as $collectionName) {
Expand Down Expand Up @@ -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);

Expand All @@ -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
Expand Down Expand Up @@ -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 = [];

Expand Down Expand Up @@ -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],
Expand All @@ -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();
}

Expand Down
47 changes: 42 additions & 5 deletions tests/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,23 @@ 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);
}

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
Expand Down Expand Up @@ -196,14 +196,51 @@ 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());
$this->assertSame('foo', $connection->getCollection('foo')->getCollectionName());
$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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do these legacy tests need to expect a deprecation message?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something catches deprecation messages and hides them. I couldn't add an assertion.

{
$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);
Expand Down
Loading