55use Illuminate \Support \Facades \DB ;
66use Illuminate \Database \QueryException ;
77
8- class RetryHelper
8+ class DBTransactionRetryHelper
99{
1010 /**
1111 * Perform a database transaction with retry logic in case of deadlocks.
1212 *
1313 * @param callable $callback The transaction logic to execute.
1414 * @param int $maxRetries Number of times to retry on deadlock.
15- * @param int $retryDelay Delay between retries in milliseconds .
15+ * @param int $retryDelay Delay between retries in seconds .
1616 * @return mixed
1717 * @throws QueryException
1818 */
19- public static function transactionWithRetry (callable $ callback , $ maxRetries = 5 , $ retryDelay = 200 )
19+ public static function transactionWithRetry (callable $ callback , int $ maxRetries = 3 , int $ retryDelay = 2 )
2020 {
2121 $ attempt = 0 ;
2222
@@ -27,16 +27,26 @@ public static function transactionWithRetry(callable $callback, $maxRetries = 5,
2727
2828 } catch (QueryException $ e ) {
2929 // Check if the error is a deadlock (MySQL error code 1213)
30- if ($ e ->getCode () === ' 1213 ' ) {
30+ if ($ e ->getCode () == 1213 || $ e -> getCode () == 40001 || $ e -> errorInfo [ 1 ] == 1213 ) {
3131 $ attempt ++;
3232
3333 if ($ attempt >= $ maxRetries ) {
34+ // Generate log when max retries are reached
35+ generateLog ([
36+ 'ExceptionName ' => get_class ($ e ),
37+ 'QueryException ' => $ e ->getMessage (),
38+ 'url ' => request ()->getUri () ?? null ,
39+ 'method ' => request ()->getMethod () ?? null ,
40+ 'token ' => request ()->header ()['authorization ' ] ?? null ,
41+ 'userId ' => request ()->user ()->id ?? null ,
42+ 'trace ' => getDebugBacktraceArray () ?? null ,
43+ ],'mysql-deadlocks-logs ' );
3444 // Throw the exception if max retries are reached
3545 throw $ e ;
3646 }
3747
3848 // Wait before retrying
39- usleep ($ retryDelay * 1000 ); // Convert milliseconds to microseconds
49+ sleep ($ retryDelay ); // Convert seconds to microseconds
4050 } else {
4151 // Re-throw exception if it's not a deadlock
4252 throw $ e ;
0 commit comments