diff --git a/lib/private/DB/Connection.php b/lib/private/DB/Connection.php index a5f41cc66c90e..2ee5548898214 100644 --- a/lib/private/DB/Connection.php +++ b/lib/private/DB/Connection.php @@ -41,6 +41,7 @@ use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection; use Doctrine\DBAL\Driver; use Doctrine\DBAL\Exception; +use Doctrine\DBAL\Exception\ConnectionLost; use Doctrine\DBAL\Platforms\MySQLPlatform; use Doctrine\DBAL\Platforms\OraclePlatform; use Doctrine\DBAL\Platforms\SqlitePlatform; @@ -78,6 +79,7 @@ class Connection extends PrimaryReadReplicaConnection { /** @var DbDataCollector|null */ protected $dbDataCollector = null; + private array $lastConnectionCheck = []; protected ?float $transactionActiveSince = null; @@ -127,10 +129,13 @@ public function __construct( public function connect($connectionName = null) { try { if ($this->_conn) { + $this->reconnectIfNeeded($connectionName); /** @psalm-suppress InternalMethod */ return parent::connect(); } + $this->lastConnectionCheck[$connectionName] = time(); + // Only trigger the event logger for the initial connect call $eventLogger = \OC::$server->get(IEventLogger::class); $eventLogger->start('connect:db', 'db connection opened'); @@ -679,4 +684,18 @@ public function rollBack() { } return $result; } + + private function reconnectIfNeeded(string $connectionName): void { + if ($this->lastConnectionCheck[$connectionName] + 30 >= time() || $this->isTransactionActive()) { + return; + } + + try { + $this->_conn->query($this->getDriver()->getDatabasePlatform()->getDummySelectSQL()); + $this->lastConnectionCheck[$connectionName] = time(); + } catch (ConnectionLost|\Exception $e) { + $this->logger->warning('Exception during connectivity check, closing and reconnecting', ['exception' => $e]); + $this->close(); + } + } }