Skip to content

Commit

Permalink
Авто переподключение к БД при ошибке gone away и deadlock
Browse files Browse the repository at this point in the history
  • Loading branch information
zerox-k committed Jan 21, 2021
1 parent 5e854ba commit 859dc2f
Showing 1 changed file with 36 additions and 8 deletions.
44 changes: 36 additions & 8 deletions src/DB.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@
class DB extends \PDO {
use Parser;

private $dsn, $username, $passwd, $options;

public function __construct($dsn, $username = null, $passwd = null, $options = null) {
if (is_array($options))
$options = array_merge([PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION], $options);
else
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$this->dsn = $dsn;
$this->username = $username;
$this->passwd = $passwd;
$this->options = $options;
parent::__construct($dsn, $username, $passwd, $options);
}

Expand All @@ -20,18 +26,40 @@ public static function create($dsn, $username = null, $passwd = null, $options =
}

public function exec($statement, $args = []) {
return parent::exec(count($args) == 0 ? $statement : $this->parse($statement, $args));
for ($i = 0; $i < 5; ++$i) {
try {
return parent::exec(count($args) == 0 ? $statement : $this->parse($statement, $args));
} catch (\PDOException $e) {
if ($i < 1 && ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 40001)) {
if ($e->errorInfo[1] == 2006)
parent::__construct($this->dsn, $this->username, $this->passwd, $this->options);
continue;
}
throw new \PDOException($e);
}
}
}

public function query($statement, $args = [], $mode = null, $arg3 = null, $ctorargs = null) {
$statement = (count($args) == 0 ? $statement : $this->parse($statement, $args));
if (!is_null($ctorargs))
return parent::query($statement, $mode, $arg3, $ctorargs);
else if (!is_null($arg3))
return parent::query($statement, $mode, $arg3);
else if (!is_null($mode))
return parent::query($statement, $mode);
return parent::query($statement);
for ($i = 0; $i < 5; ++$i) {
try {
if (!is_null($ctorargs))
return parent::query($statement, $mode, $arg3, $ctorargs);
else if (!is_null($arg3))
return parent::query($statement, $mode, $arg3);
else if (!is_null($mode))
return parent::query($statement, $mode);
return parent::query($statement);
} catch (\PDOException $e) {
if ($i < 1 && ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 40001)) {
if ($e->errorInfo[1] == 2006)
parent::__construct($this->dsn, $this->username, $this->passwd, $this->options);
continue;
}
throw new \PDOException($e);
}
}
}

public function prepare($statement, $args = [], array $driver_options = array()) {
Expand Down

0 comments on commit 859dc2f

Please sign in to comment.