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 b132491
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Doctrine\Deprecations\Deprecation;
use LogicException;
use SensitiveParameter;
use Symfony\Bridge\Doctrine\ConnectionLossAwareHandler;
use Throwable;
use Traversable;

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

private SchemaManagerFactory $schemaManagerFactory;

private static bool $isChecking = false;

private static ?int $lastCheckedAt = null;

private static ?int $checkFrequency = null;

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

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

if ($this->_conn !== null) {
if (! class_exists(ConnectionLossAwareHandler::class) || null === self::$checkFrequency) {
return false;
}

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

Check warning on line 388 in src/Connection.php

View check run for this annotation

Codecov / codecov/patch

src/Connection.php#L386-L388

Added lines #L386 - L388 were not covered by tests

ConnectionLossAwareHandler::reconnectOnFailure($this);

Check warning on line 390 in src/Connection.php

View check run for this annotation

Codecov / codecov/patch

src/Connection.php#L390

Added line #L390 was not covered by tests

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

Check warning on line 393 in src/Connection.php

View check run for this annotation

Codecov / codecov/patch

src/Connection.php#L392-L393

Added lines #L392 - L393 were not covered by tests
}
}

return false;
}

Expand Down

0 comments on commit b132491

Please sign in to comment.