From 06f8d1779d4b8ec935dc1bd77e3fb70215275868 Mon Sep 17 00:00:00 2001
From: Jared Hancock <jared@osticket.com>
Date: Tue, 28 Jan 2014 23:29:15 -0600
Subject: [PATCH] mysqli: Retry on deadlock-found error

If MySQL error #1213 (deadlock found when trying to get lock) is returned
from query, it is safe to retry the query.

This patch will retry queries up to two times for a total of three. If the
query cannot be executed without error #1213 after the third time, the error
is logged as usual, and the system continues with the failed query.
---
 include/mysqli.php | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/include/mysqli.php b/include/mysqli.php
index 3b535919e..d8ce115cc 100644
--- a/include/mysqli.php
+++ b/include/mysqli.php
@@ -125,7 +125,13 @@ function db_create_database($database, $charset='utf8',
 function db_query($query, $logError=true) {
     global $ost, $__db;
 
-    $res = $__db->query($query);
+    $tries = 3;
+    do {
+        $res = $__db->query($query);
+        // Retry the query due to deadlock error (#1213)
+        // TODO: Consider retry on #1205 (lock wait timeout exceeded)
+        // TODO: Log warning
+    } while (!$res && --$tries && $__db->errno == 1213);
 
     if(!$res && $logError && $ost) { //error reporting
         $msg='['.$query.']'."\n\n".db_error();
-- 
GitLab