Skip to content

Commit

Permalink
In long-running processes, allows checking the database connection by…
Browse files Browse the repository at this point in the history
… 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.
  • Loading branch information
alli83 committed Apr 4, 2024
1 parent e5db00e commit eb3fe0e
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Doctrine\DBAL\Exception\ConnectionLost;
use Doctrine\DBAL\Exception\DriverException;
use Doctrine\DBAL\Exception\InvalidArgumentException;
use Doctrine\DBAL\Exception as DBALException;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
use Doctrine\DBAL\Query\QueryBuilder;
Expand All @@ -29,6 +30,7 @@
use Doctrine\Deprecations\Deprecation;
use LogicException;
use SensitiveParameter;
use Symfony\Bridge\Doctrine\ConnectionLossAwareHandler;
use Throwable;
use Traversable;

Expand Down Expand Up @@ -166,6 +168,12 @@ class Connection

private SchemaManagerFactory $schemaManagerFactory;

private static bool $isChecking = false;

private static ?int $lastCheckedAt = null;

private ?int $checkFrequency;

/**
* Initializes a new instance of the Connection class.
*
Expand All @@ -186,6 +194,7 @@ public function __construct(
?Configuration $config = null,
?EventManager $eventManager = null
) {
$this->checkFrequency = $params['check_connection_frequency'] ?? null;
$this->_driver = $driver;
$this->params = $params;

Expand Down Expand Up @@ -371,6 +380,21 @@ public function connect()
);

if ($this->_conn !== null) {
if (null === $this->checkFrequency) {
return false;
}

if (! self::$isChecking) {
if (null === self::$lastCheckedAt || time() - self::$lastCheckedAt >= $this->checkFrequency) {
self::$isChecking = true;

$this->reconnectOnFailure($this);

self::$lastCheckedAt = time();
self::$isChecking = false;
}
}

return false;
}

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

return $this->executeStatement($sql);
}

private function reconnectOnFailure(Connection $connection)
{
try {
$connection->executeQuery($connection->getDatabasePlatform($connection)->getDummySelectSQL());
} catch (DBALException) {
$connection->close();
// Attempt to reestablish the lazy connection by sending another query.
$connection->executeQuery($connection->getDatabasePlatform($connection)->getDummySelectSQL());
}
}
}

0 comments on commit eb3fe0e

Please sign in to comment.