diff --git a/src/RetryConnection.php b/src/RetryConnection.php new file mode 100644 index 0000000..3a7ea88 --- /dev/null +++ b/src/RetryConnection.php @@ -0,0 +1,87 @@ +retries = $numberRetries; + } + + public function prepexec($stmt, $values = null) + { + $retries = 0; + $retryHandler = function () use (&$retryHandler, &$retries, $stmt, $values): PDOStatement { + try { + return parent::prepexec($stmt, $values); + } catch (Exception $err) { + if ($retries < $this->retries && $this->isRetryable($err)) { + $retries++; + + $this->disconnect(); + + return $retryHandler(); + } + + throw $err; + } + }; + + return $retryHandler(); + } + + /** + * Get whether the given (PDO) exception can be fixed by reconnecting to the database. + * + * @param Exception $err + * + * @return bool + */ + public static function isRetryable(Exception $err): bool + { + $message = $err->getMessage(); + foreach (static::$retryableErrors as $error) { + if (strpos($message, $error) !== false) { + return true; + } + } + + return false; + } +}