Skip to content

Commit 1c83dab

Browse files
committed
PHPORM-248 register command subscriber only when logs are enabled
1 parent 5c7e240 commit 1c83dab

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed

src/Connection.php

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ class Connection extends BaseConnection
4848
*/
4949
protected $connection;
5050

51-
private ?CommandSubscriber $commandSubscriber;
51+
private ?CommandSubscriber $commandSubscriber = null;
5252

5353
/**
5454
* Create a new database connection instance.
@@ -65,8 +65,6 @@ public function __construct(array $config)
6565

6666
// Create the connection
6767
$this->connection = $this->createConnection($dsn, $config, $options);
68-
$this->commandSubscriber = new CommandSubscriber($this);
69-
$this->connection->addSubscriber($this->commandSubscriber);
7068

7169
// Select database
7270
$this->db = $this->connection->selectDatabase($this->getDefaultDatabaseName($dsn, $config));
@@ -141,6 +139,36 @@ public function getDatabaseName()
141139
return $this->getMongoDB()->getDatabaseName();
142140
}
143141

142+
public function enableQueryLog()
143+
{
144+
parent::enableQueryLog();
145+
146+
$this->commandSubscriber = new CommandSubscriber($this);
147+
$this->connection->addSubscriber($this->commandSubscriber);
148+
}
149+
150+
public function disableQueryLog()
151+
{
152+
parent::disableQueryLog(); // TODO: Change the autogenerated stub
153+
154+
$this->connection->removeSubscriber($this->commandSubscriber);
155+
$this->commandSubscriber = null;
156+
}
157+
158+
protected function withFreshQueryLog($callback)
159+
{
160+
try {
161+
return parent::withFreshQueryLog($callback);
162+
} finally {
163+
// The parent method enable query log using enableQueryLog()
164+
// but disables it by setting $loggingQueries to false. We need to
165+
// remove the subscriber for performance.
166+
if (! $this->loggingQueries) {
167+
$this->disableQueryLog();
168+
}
169+
}
170+
}
171+
144172
/**
145173
* Get the name of the default database based on db config or try to detect it from dsn.
146174
*

tests/ConnectionTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,21 @@ public function testQueryLog()
277277
}
278278
}
279279

280+
public function testDisableQueryLog()
281+
{
282+
// Disabled by default
283+
DB::table('items')->get();
284+
$this->assertCount(0, DB::getQueryLog());
285+
286+
DB::enableQueryLog();
287+
DB::table('items')->get();
288+
$this->assertCount(1, DB::getQueryLog());
289+
290+
DB::disableQueryLog();
291+
DB::table('items')->get();
292+
$this->assertCount(1, DB::getQueryLog());
293+
}
294+
280295
public function testSchemaBuilder()
281296
{
282297
$schema = DB::connection('mongodb')->getSchemaBuilder();

0 commit comments

Comments
 (0)