Added mysql query retry after database deadlock detection.
[fa-stable.git] / includes / db / connect_db_mysql.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 define('DB_DUPLICATE_ERROR', 1062);
13 define('SQL_MODE', ''); // STRICT_ALL_TABLES,NO_ZERO_IN_DATE ?
14
15 function set_global_connection($company=-1)
16 {
17         global $db, $path_to_root, $db_connections;
18
19         include ($path_to_root . "/config_db.php");
20         if ($company == -1) 
21                 $company = user_company();
22
23         cancel_transaction(); // cancel all aborted transactions if any
24
25         $_SESSION["wa_current_user"]->cur_con = $company;
26
27         $connection = $db_connections[$company];
28
29         $db = mysql_connect($connection["host"], $connection["dbuser"], $connection["dbpassword"]);
30                 mysql_select_db($connection["dbname"], $db);
31         ///// From MySql release 5.6.6 the sql_mode is no longer empty as it was prior to
32         ///// this release. Just for safety we make it empty for all 5.6 release and higher.
33         ///// This non empty sql_mode values can interphere with FA, so all is set empty during
34         ///// our sessions.
35         ///// We are, however, investigating the existing code to be compatible in the future.
36                 db_query("SET sql_mode = '".SQL_MODE."'");
37         /////
38         return $db;
39 }
40
41 //DB wrapper functions to change only once for whole application
42
43 function db_query($sql, $err_msg=null)
44 {
45         global $db, $SysPrefs, $sql_queries, $Ajax, $db_connections, $db_last_inserted_id;
46
47         // set current db prefix
48         $comp = isset($_SESSION["wa_current_user"]->cur_con) ? $_SESSION["wa_current_user"]->cur_con : 0;
49         $cur_prefix = $db_connections[$comp]['tbpref'];
50         $sql = str_replace(TB_PREF, $cur_prefix, $sql);
51
52         if ($SysPrefs->show_sql)
53         {
54                 $Ajax->activate('footer_debug');
55                 $sql_queries .= "<pre>$sql</pre>\n<hr>";
56         }
57
58         db_profile(); // mysql profiling
59
60         $retry = MAX_DEADLOCK_RETRY;
61         do {
62                 $result = mysql_query($db, $sql);
63                 if (mysql_errno($db) == 1213)   { // deadlock detected
64                         sleep(1); $retry--;
65                 } else
66                         $retry = 0;
67         } while ($retry);
68
69         db_profile($sql);
70
71         if($SysPrefs->sql_trail) {
72                 $db_last_inserted_id = mysql_insert_id($db);    // preserve in case trail insert is done
73                 if ($SysPrefs->select_trail || (strstr($sql, 'SELECT') === false)) {
74                         mysql_query(
75                         "INSERT INTO ".$cur_prefix."sql_trail
76                                 (`sql`, `result`, `msg`)
77                                 VALUES(".db_escape($sql).",".($result ? 1 : 0).",
78                                 ".db_escape($err_msg).")", $db);
79                 }
80         }
81
82         if ($err_msg != null || $SysPrefs->go_debug) {
83                 $exit = $err_msg != null;
84                 if (function_exists('xdebug_call_file'))
85                         $err_msg = '<br>At file '.xdebug_call_file().':'.xdebug_call_line().':<br>'.$err_msg;
86                 check_db_error($err_msg, $sql, $exit);
87         }
88         return $result;
89 }
90
91 function db_fetch_row($result)
92 {
93
94         return mysql_fetch_row($result);
95 }
96
97 function db_fetch_assoc($result)
98 {
99
100         return mysql_fetch_assoc($result);
101 }
102
103 function db_fetch($result)
104 {
105
106         return mysql_fetch_array($result);
107 }
108
109 function db_seek(&$result,$record)
110 {
111         return mysql_data_seek($result, $record);
112 }
113
114 function db_free_result($result)
115 {
116         if ($result)
117                 mysql_free_result($result);
118 }
119
120 function db_num_rows($result)
121 {
122         return mysql_num_rows($result);
123 }
124
125 function db_num_fields($result)
126 {
127         return mysql_num_fields($result);
128 }
129
130 function db_escape($value = "", $nullify = false)
131 {
132         $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
133         $value = html_specials_encode($value);
134
135         //reset default if second parameter is skipped
136         $nullify = ($nullify === null) ? (false) : ($nullify);
137
138         //check for null/unset/empty strings
139         if ((!isset($value)) || (is_null($value)) || ($value === "")) {
140                 $value = ($nullify) ? ("NULL") : ("''");
141         } else {
142                 if (is_string($value)) {
143                 //value is a string and should be quoted; determine best method based on available extensions
144                         if (function_exists('mysql_real_escape_string')) {
145                                 $value = "'" . mysql_real_escape_string($value) . "'";
146                         } else {
147                           $value = "'" . mysql_escape_string($value) . "'";
148                         }
149                 } else if (!is_numeric($value)) {
150                         //value is not a string nor numeric
151                         display_error("ERROR: incorrect data type send to sql query");
152                         echo '<br><br>';
153                         exit();
154                 }
155         }
156         return $value;
157 }
158
159 function db_error_no()
160 {
161         global $db;
162         return mysql_errno($db);
163 }
164
165 function db_error_msg($conn)
166 {
167         return mysql_error($conn);
168 }
169
170 function db_insert_id()
171 {
172         global $db_last_inserted_id, $SysPrefs, $db;
173
174         return $SysPrefs->sql_trail ? $db_last_inserted_id : mysql_insert_id($db);
175 }
176
177 function db_num_affected_rows()
178 {
179         global $db;
180         return mysql_affected_rows($db);
181 }
182
183 function db_field_name($result, $n)
184 {
185         return mysql_field_name($result, $n);
186 }
187
188 function db_create_db($connection)
189 {
190         $db = mysql_connect($connection["host"] ,
191                 $connection["dbuser"], $connection["dbpassword"]);
192
193         if (!mysql_select_db($connection["dbname"], $db))
194         {
195                 $sql = "CREATE DATABASE IF NOT EXISTS " . $connection["dbname"] . "";
196                 if (!mysql_query($sql) || !mysql_select_db($connection["dbname"], $db))
197                         return 0;
198         }
199         return $db;
200 }
201
202 function db_drop_db($connection)
203 {
204
205         if ($connection["tbpref"] == "")
206         {
207                 $sql = "DROP DATABASE IF EXISTS " . $connection["dbname"] . "";
208                 return mysql_query($sql);
209         }
210         else
211         {
212         $res = db_query("show table status");
213         $all_tables = array();
214         while($row = db_fetch($res))
215                 $all_tables[] = $row;
216         // get table structures
217                 foreach ($all_tables as $table)
218                 {
219                         if (strpos($table['Name'], $connection["tbpref"]) === 0)
220                                 db_query("DROP TABLE `".$table['Name'] . "`");
221                 }
222                 //deleting the tables, how??
223                 return true;
224         }
225 }
226
227 function db_close($dbase = null)
228 {
229         global $db;
230         
231         if (!$dbase)
232                 $dbase = $db;
233         return mysql_close($dbase);
234 }
235
236 function db_extension_exists()
237 {
238         return function_exists('mysql_connect');
239 }
240
241 function db_escape_function($string)
242 {
243         return (function_exists('mysql_real_escape_string') ? mysql_real_escape_string($string) : mysql_escape_string($string));
244 }
245
246 /*
247         Set mysql client encoding.
248         Default is is encoding used by default language.
249 */
250 function db_set_encoding($ui_encoding=null)
251 {
252         global $dflt_lang, $installed_languages;
253
254         if (!isset($ui_encoding))
255         {
256                 $lang = array_search_value($dflt_lang, $installed_languages, 'code');
257                 $ui_encoding = strtoupper($lang['encoding']);
258         }
259
260         if ($mysql_enc = get_mysql_encoding_name($ui_encoding))
261                 mysql_set_charset($mysql_enc);
262 }
263
264 function db_get_charset($db)
265 {
266         return mysql_client_encoding();
267 }
268
269 function db_set_charset($db, $charset)
270 {
271         return mysql_set_charset($charset, $db);
272 }