Skip to content

Commit 7961014

Browse files
authored
Merge pull request #534 from utopia-php/feat-connection-checker
Add custom connection checker
2 parents f3c9aa9 + 56f58fa commit 7961014

File tree

3 files changed

+49
-13
lines changed

3 files changed

+49
-13
lines changed

composer.lock

Lines changed: 10 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Database/Connection.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace Utopia\Database;
4+
5+
use Swoole\Database\DetectsLostConnections;
6+
7+
class Connection
8+
{
9+
/**
10+
* @var array<string>
11+
*/
12+
protected static array $errors = [
13+
'Max connect timeout reached'
14+
];
15+
16+
/**
17+
* Check if the given throwable was caused by a database connection error.
18+
*
19+
* @param \Throwable $e
20+
* @return bool
21+
*/
22+
public static function hasError(\Throwable $e): bool
23+
{
24+
/** @phpstan-ignore-next-line can't find static method */
25+
if (DetectsLostConnections::causedByLostConnection($e)) {
26+
return true;
27+
}
28+
29+
$message = $e->getMessage();
30+
foreach (static::$errors as $needle) {
31+
if (\mb_strpos($message, $needle) !== false) {
32+
return true;
33+
}
34+
}
35+
36+
return false;
37+
}
38+
}

src/Database/PDO.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
namespace Utopia\Database;
44

5-
use Swoole\Database\DetectsLostConnections;
65
use Utopia\CLI\Console;
76

87
/**
@@ -45,8 +44,7 @@ public function __call(string $method, array $args): mixed
4544
try {
4645
return $this->pdo->{$method}(...$args);
4746
} catch (\Throwable $e) {
48-
/** @phpstan-ignore-next-line can't find static method */
49-
if (DetectsLostConnections::causedByLostConnection($e)) {
47+
if (Connection::hasError($e)) {
5048
Console::warning('[Database] Lost connection detected. Reconnecting...');
5149
$this->reconnect();
5250
return $this->pdo->{$method}(...$args);

0 commit comments

Comments
 (0)