diff --git a/src/Connection.php b/src/Connection.php index a76ddc010..84ca97aba 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -48,7 +48,7 @@ class Connection extends BaseConnection */ protected $connection; - private ?CommandSubscriber $commandSubscriber; + private ?CommandSubscriber $commandSubscriber = null; /** * Create a new database connection instance. @@ -65,8 +65,6 @@ public function __construct(array $config) // Create the connection $this->connection = $this->createConnection($dsn, $config, $options); - $this->commandSubscriber = new CommandSubscriber($this); - $this->connection->addSubscriber($this->commandSubscriber); // Select database $this->db = $this->connection->selectDatabase($this->getDefaultDatabaseName($dsn, $config)); @@ -141,6 +139,40 @@ public function getDatabaseName() return $this->getMongoDB()->getDatabaseName(); } + public function enableQueryLog() + { + parent::enableQueryLog(); + + if (! $this->commandSubscriber) { + $this->commandSubscriber = new CommandSubscriber($this); + $this->connection->addSubscriber($this->commandSubscriber); + } + } + + public function disableQueryLog() + { + parent::disableQueryLog(); + + if ($this->commandSubscriber) { + $this->connection->removeSubscriber($this->commandSubscriber); + $this->commandSubscriber = null; + } + } + + protected function withFreshQueryLog($callback) + { + try { + return parent::withFreshQueryLog($callback); + } finally { + // The parent method enable query log using enableQueryLog() + // but disables it by setting $loggingQueries to false. We need to + // remove the subscriber for performance. + if (! $this->loggingQueries) { + $this->disableQueryLog(); + } + } + } + /** * Get the name of the default database based on db config or try to detect it from dsn. * @@ -203,8 +235,7 @@ public function ping(): void /** @inheritdoc */ public function disconnect() { - $this->connection?->removeSubscriber($this->commandSubscriber); - $this->commandSubscriber = null; + $this->disableQueryLog(); $this->connection = null; } diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index 4f9dfa10c..fe3272943 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -277,6 +277,31 @@ public function testQueryLog() } } + public function testDisableQueryLog() + { + // Disabled by default + DB::table('items')->get(); + $this->assertCount(0, DB::getQueryLog()); + + DB::enableQueryLog(); + DB::table('items')->get(); + $this->assertCount(1, DB::getQueryLog()); + + // Enable twice should only log once + DB::enableQueryLog(); + DB::table('items')->get(); + $this->assertCount(2, DB::getQueryLog()); + + DB::disableQueryLog(); + DB::table('items')->get(); + $this->assertCount(2, DB::getQueryLog()); + + // Disable twice should not log + DB::disableQueryLog(); + DB::table('items')->get(); + $this->assertCount(2, DB::getQueryLog()); + } + public function testSchemaBuilder() { $schema = DB::connection('mongodb')->getSchemaBuilder();