-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathPDO.php
More file actions
71 lines (64 loc) · 1.51 KB
/
PDO.php
File metadata and controls
71 lines (64 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
namespace Utopia\Database;
use Utopia\CLI\Console;
/**
* A PDO wrapper that forwards method calls to the internal PDO instance.
*
* @mixin \PDO
*/
class PDO
{
protected \PDO $pdo;
/**
* @param string $dsn
* @param ?string $username
* @param ?string $password
* @param array<mixed> $config
*/
public function __construct(
protected string $dsn,
protected ?string $username,
protected ?string $password,
protected array $config = []
) {
$this->pdo = new \PDO(
$this->dsn,
$this->username,
$this->password,
$this->config
);
}
/**
* @param string $method
* @param array<mixed> $args
* @return mixed
* @throws \Throwable
*/
public function __call(string $method, array $args): mixed
{
try {
return $this->pdo->{$method}(...$args);
} catch (\Throwable $e) {
if (Connection::hasError($e)) {
Console::warning('[Database] Lost connection detected. Reconnecting...');
$this->reconnect();
return $this->pdo->{$method}(...$args);
}
throw $e;
}
}
/**
* Create a new connection to the database
*
* @return void
*/
public function reconnect(): void
{
$this->pdo = new \PDO(
$this->dsn,
$this->username,
$this->password,
$this->config
);
}
}