Skip to content

Commit e0e30e3

Browse files
committed
Add custom connection checker
1 parent f3c9aa9 commit e0e30e3

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/Database/Connection.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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 hasDatabaseError(\Throwable $e): bool
23+
{
24+
if (DetectsLostConnections::causedByLostConnection($e)) {
25+
return true;
26+
}
27+
28+
$message = $e->getMessage();
29+
foreach (static::$errors as $needle) {
30+
if (\mb_strpos($message, $needle) !== false) {
31+
return true;
32+
}
33+
}
34+
35+
return false;
36+
}
37+
}

src/Database/PDO.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public function __call(string $method, array $args): mixed
4646
return $this->pdo->{$method}(...$args);
4747
} catch (\Throwable $e) {
4848
/** @phpstan-ignore-next-line can't find static method */
49-
if (DetectsLostConnections::causedByLostConnection($e)) {
49+
if (Connection::hasDatabaseError($e)) {
5050
Console::warning('[Database] Lost connection detected. Reconnecting...');
5151
$this->reconnect();
5252
return $this->pdo->{$method}(...$args);

0 commit comments

Comments
 (0)