From be4e327739853da881193cec8a7df85663b8fd04 Mon Sep 17 00:00:00 2001 From: Yonas Habteab Date: Mon, 17 Jul 2023 11:36:31 +0200 Subject: [PATCH] Add retryable connection --- src/RetryConnection.php | 87 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/RetryConnection.php 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; + } +}