Skip to content

Commit c3251e9

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 c3251e9

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/Connection.php

+35
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;
@@ -29,6 +30,7 @@
2930
use Doctrine\Deprecations\Deprecation;
3031
use LogicException;
3132
use SensitiveParameter;
33+
use Symfony\Bridge\Doctrine\ConnectionLossAwareHandler;
3234
use Throwable;
3335
use Traversable;
3436

@@ -166,6 +168,12 @@ class Connection
166168

167169
private SchemaManagerFactory $schemaManagerFactory;
168170

171+
private static bool $isChecking = false;
172+
173+
private static ?int $lastCheckedAt = null;
174+
175+
private ?int $checkFrequency;
176+
169177
/**
170178
* Initializes a new instance of the Connection class.
171179
*
@@ -186,6 +194,7 @@ public function __construct(
186194
?Configuration $config = null,
187195
?EventManager $eventManager = null
188196
) {
197+
$this->checkFrequency = $params['check_connection_frequency'] ?? null;
189198
$this->_driver = $driver;
190199
$this->params = $params;
191200

@@ -371,6 +380,21 @@ public function connect()
371380
);
372381

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

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

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

0 commit comments

Comments
 (0)