Skip to content

Commit cacec40

Browse files
committed
In long-running processes, allows checking the database connection by pinging it, thus avoiding exceptions. Additionally, it provides the flexibility to configure the frequency of the check to be performed in the case of long-running processes.
1 parent e5db00e commit cacec40

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/Connection.php

+34
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use Doctrine\DBAL\Exception\ConnectionLost;
1818
use Doctrine\DBAL\Exception\DriverException;
1919
use Doctrine\DBAL\Exception\InvalidArgumentException;
20+
use Doctrine\DBAL\Exception as DBALException;
2021
use Doctrine\DBAL\Platforms\AbstractPlatform;
2122
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
2223
use Doctrine\DBAL\Query\QueryBuilder;
@@ -166,6 +167,12 @@ class Connection
166167

167168
private SchemaManagerFactory $schemaManagerFactory;
168169

170+
private static bool $isChecking = false;
171+
172+
private static ?int $lastCheckedAt = null;
173+
174+
private ?int $checkFrequency;
175+
169176
/**
170177
* Initializes a new instance of the Connection class.
171178
*
@@ -186,6 +193,7 @@ public function __construct(
186193
?Configuration $config = null,
187194
?EventManager $eventManager = null
188195
) {
196+
$this->checkFrequency = $params['check_connection_frequency'] ?? null;
189197
$this->_driver = $driver;
190198
$this->params = $params;
191199

@@ -371,6 +379,21 @@ public function connect()
371379
);
372380

373381
if ($this->_conn !== null) {
382+
if (null === $this->checkFrequency) {
383+
return false;
384+
}
385+
386+
if (! self::$isChecking) {
387+
if (null === self::$lastCheckedAt || time() - self::$lastCheckedAt >= $this->checkFrequency) {
388+
self::$isChecking = true;
389+
390+
$this->reconnectOnFailure();
391+
392+
self::$lastCheckedAt = time();
393+
self::$isChecking = false;
394+
}
395+
}
396+
374397
return false;
375398
}
376399

@@ -2002,4 +2025,15 @@ public function exec(string $sql): int
20022025

20032026
return $this->executeStatement($sql);
20042027
}
2028+
2029+
private function reconnectOnFailure()
2030+
{
2031+
try {
2032+
$this->executeQuery($this->getDatabasePlatform($this)->getDummySelectSQL());
2033+
} catch (DBALException) {
2034+
$this->close();
2035+
// Attempt to reestablish the lazy connection by sending another query.
2036+
$this->executeQuery($this->getDatabasePlatform($this)->getDummySelectSQL());
2037+
}
2038+
}
20052039
}

0 commit comments

Comments
 (0)