4 * @package dbal_firebird
5 * @version $Id: firebird.php,v 1.2 2005/06/10 08:52:03 devalley Exp $
6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('SQL_LAYER'))
17 define('SQL_LAYER', 'firebird');
20 * @package dbal_firebird
21 * Firebird/Interbase Database Abstraction Layer
22 * Minimum Requirement is Firebird 1.5+/Interbase 7.1+
28 var $return_on_error = false;
29 var $transaction = false;
32 var $open_queries = array();
34 var $last_query_text = '';
36 function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false)
38 $this->persistency = $persistency;
39 $this->user = $sqluser;
40 $this->server = $sqlserver . (($port) ? ':' . $port : '');
41 $this->dbname = $database;
43 $this->db_connect_id = ($this->persistency) ? @ibase_pconnect($this->server . ':' . $this->dbname, $this->user, $sqlpassword, false, false, 3) : @ibase_connect($this->server . ':' . $this->dbname, $this->user, $sqlpassword, false, false, 3);
45 return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
53 if (!$this->db_connect_id)
58 if ($this->transaction)
60 @ibase_commit($this->db_connect_id);
63 if (sizeof($this->open_queries))
65 foreach ($this->open_queries as $i_query_id => $query_id)
67 @ibase_free_query($query_id);
71 return @ibase_close($this->db_connect_id);
74 function sql_return_on_error($fail = false)
76 $this->return_on_error = $fail;
79 function sql_num_queries()
81 return $this->num_queries;
84 function sql_transaction($status = 'begin')
89 $this->transaction = true;
93 $result = @ibase_commit();
94 $this->transaction = false;
103 $result = @ibase_rollback();
104 $this->transaction = false;
115 function sql_query($query = '', $cache_ttl = 0)
121 $this->last_query_text = $query;
122 $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
124 if (!$this->query_result)
126 $this->num_queries++;
128 if (($this->query_result = @ibase_query($this->db_connect_id, $query)) === false)
130 $this->sql_error($query);
133 // TODO: have to debug the commit states in firebird
134 if (!$this->transaction)
139 if ($cache_ttl && method_exists($cache, 'sql_save'))
141 $cache->sql_save($query, $this->query_result, $cache_ttl);
150 return ($this->query_result) ? $this->query_result : false;
153 function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
157 $this->query_result = false;
159 $query = 'SELECT FIRST ' . $total . ((!empty($offset)) ? ' SKIP ' . $offset : '') . substr($query, 6);
161 return $this->sql_query($query, $cache_ttl);
169 // Idea for this from Ikonboard
170 function sql_build_array($query, $assoc_ary = false)
172 if (!is_array($assoc_ary))
179 if ($query == 'INSERT')
181 foreach ($assoc_ary as $key => $var)
189 elseif (is_string($var))
191 $values[] = "'" . $this->sql_escape($var) . "'";
195 $values[] = (is_bool($var)) ? intval($var) : $var;
199 $query = ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
201 else if ($query == 'UPDATE' || $query == 'SELECT')
204 foreach ($assoc_ary as $key => $var)
208 $values[] = "$key = NULL";
210 elseif (is_string($var))
212 $values[] = "$key = '" . $this->sql_escape($var) . "'";
216 $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var";
219 $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
225 // Other query methods
227 // NOTE :: Want to remove _ALL_ reliance on sql_numrows from core code ...
228 // don't want this here by a middle Milestone
229 function sql_numrows($query_id = false)
234 function sql_affectedrows()
236 // TODO: hmm, maybe doing something similar as in mssql-odbc.php?
237 return ($this->query_result) ? true : false;
240 function sql_fetchrow($query_id = false)
246 $query_id = $this->query_result;
249 if (isset($cache->sql_rowset[$query_id]))
251 return $cache->sql_fetchrow($query_id);
255 $cur_row = @ibase_fetch_object($query_id, IBASE_TEXT);
262 foreach (get_object_vars($cur_row) as $key => $value)
264 $row[strtolower($key)] = trim(str_replace("\\0", "\0", str_replace("\\n", "\n", $value)));
266 return ($query_id) ? $row : false;
269 function sql_fetchrowset($query_id = false)
273 $query_id = $this->query_result;
278 unset($this->rowset[$query_id]);
279 unset($this->row[$query_id]);
282 while ($this->rowset[$query_id] = get_object_vars(@ibase_fetch_object($query_id, IBASE_TEXT)))
284 $result[] = $this->rowset[$query_id];
295 function sql_fetchfield($field, $rownum = -1, $query_id = 0)
299 $query_id = $this->query_result;
306 // erm... ok, my bad, we always use zero. :/
307 for ($i = 0; $i <= $rownum; $i++)
309 $row = $this->sql_fetchrow($query_id);
316 if (empty($this->row[$query_id]) && empty($this->rowset[$query_id]))
318 if ($this->sql_fetchrow($query_id))
320 $result = $this->row[$query_id][$field];
325 if ($this->rowset[$query_id])
327 $result = $this->rowset[$query_id][$field];
329 else if ($this->row[$query_id])
331 $result = $this->row[$query_id][$field];
343 function sql_rowseek($rownum, $query_id = 0)
347 $query_id = $this->query_result;
350 for($i = 1; $i < $rownum; $i++)
352 if (!$this->sql_fetchrow($query_id))
361 function sql_nextid()
363 if ($this->query_result && preg_match('#^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)#is', $this->last_query_text, $tablename))
365 $query = "SELECT GEN_ID('" . $tablename[1] . "_gen', 0) AS new_id
367 if (!($temp_q_id = @ibase_query($this->db_connect_id, $query)))
372 $temp_result = @ibase_fetch_object($temp_q_id);
373 $this->sql_freeresult($temp_q_id);
375 return ($temp_result) ? $temp_result->last_value : false;
379 function sql_freeresult($query_id = false)
383 $query_id = $this->query_result;
386 if (!$this->transaction && $query_id)
391 return ($query_id) ? @ibase_free_result($query_id) : false;
394 function sql_escape($msg)
396 return (@ini_get('magic_quotes_sybase') || strtolower(@ini_get('magic_quotes_sybase')) == 'on') ? str_replace('\\\'', '\'', addslashes($msg)) : str_replace('\'', '\'\'', stripslashes($msg));
399 function sql_error($sql = '')
401 if (!$this->return_on_error)
403 $this_page =(!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
404 $this_page .= '&' .((!empty($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : $_ENV['QUERY_STRING']);
406 $message = '<u>SQL ERROR</u> [ ' . SQL_LAYER . ' ]<br /><br />' . @ibase_errmsg() . '<br /><br /><u>CALLING PAGE</u><br /><br />' . $this_page .(($sql != '') ? '<br /><br /><u>SQL</u><br /><br />' . $sql : '') . '<br />';
408 if ($this->transaction)
410 $this->sql_transaction('rollback');
413 trigger_error($message, E_USER_ERROR);
416 $result['message'] = @ibase_errmsg();
417 $result['code'] = '';
422 function sql_report($mode, $query = '')
424 if (empty($_GET['explain']))
429 global $cache, $starttime, $phpbb_root_path;
430 static $curtime, $query_hold, $html_hold;
431 static $sql_report = '';
432 static $cache_num_queries = 0;
434 if (!$query && !empty($query_hold))
436 $query = $query_hold;
448 $mtime = explode(' ', microtime());
449 $totaltime = $mtime[0] + $mtime[1] - $starttime;
451 echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8869-1"><meta http-equiv="Content-Style-Type" content="text/css"><link rel="stylesheet" href="' . $phpbb_root_path . 'adm/subSilver.css" type="text/css"><style type="text/css">' . "\n";
452 echo 'th { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic3.gif\') }' . "\n";
453 echo 'td.cat { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic1.gif\') }' . "\n";
454 echo '</style><title>' . $msg_title . '</title></head><body>';
455 echo '<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td><a href="' . htmlspecialchars(preg_replace('/&explain=([^&]*)/', '', $_SERVER['REQUEST_URI'])) . '"><img src="' . $phpbb_root_path . 'adm/images/header_left.jpg" width="200" height="60" alt="phpBB Logo" title="phpBB Logo" border="0"/></a></td><td width="100%" background="' . $phpbb_root_path . 'adm/images/header_bg.jpg" height="60" align="right" nowrap="nowrap"><span class="maintitle">SQL Report</span> </td></tr></table><br clear="all"/><table width="95%" cellspacing="1" cellpadding="4" border="0" align="center"><tr><td height="40" align="center" valign="middle"><b>Page generated in ' . round($totaltime, 4) . " seconds with {$this->num_queries} queries" . (($cache_num_queries) ? " + $cache_num_queries " . (($cache_num_queries == 1) ? 'query' : 'queries') . ' returning data from cache' : '') . '</b></td></tr><tr><td align="center" nowrap="nowrap">Time spent on MySQL queries: <b>' . round($this->sql_time, 5) . 's</b> | Time spent on PHP: <b>' . round($totaltime - $this->sql_time, 5) . 's</b></td></tr></table><table width="95%" cellspacing="1" cellpadding="4" border="0" align="center"><tr><td>';
457 echo '</td></tr></table><br /></body></html>';
462 $query_hold = $query;
465 $curtime = explode(' ', microtime());
466 $curtime = $curtime[0] + $curtime[1];
470 $endtime = explode(' ', microtime());
471 $endtime = $endtime[0] + $endtime[1];
473 $result = @ibase_query($this->db_connect_id, $query);
474 while ($void = @ibase_fetch_object($result, IBASE_TEXT))
476 // Take the time spent on parsing rows into account
478 $splittime = explode(' ', microtime());
479 $splittime = $splittime[0] + $splittime[1];
481 $time_cache = $endtime - $curtime;
482 $time_db = $splittime - $endtime;
483 $color = ($time_db > $time_cache) ? 'green' : 'red';
485 $sql_report .= '<hr width="100%"/><br /><table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0"><tr><th>Query results obtained from the cache</th></tr><tr><td class="row1"><textarea style="font-family:\'Courier New\',monospace;width:100%" rows="5">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></table><p align="center">';
487 $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed [cache]: <b style="color: ' . $color . '">' . sprintf('%.5f', ($time_cache)) . 's</b> | Elapsed [db]: <b>' . sprintf('%.5f', $time_db) . 's</b></p>';
489 // Pad the start time to not interfere with page timing
490 $starttime += $time_db;
492 @ibase_freeresult($result);
493 $cache_num_queries++;
497 $endtime = explode(' ', microtime());
498 $endtime = $endtime[0] + $endtime[1];
500 $sql_report .= '<hr width="100%"/><br /><table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0"><tr><th>Query #' . $this->num_queries . '</th></tr><tr><td class="row1"><textarea style="font-family:\'Courier New\',monospace;width:100%" rows="5">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></table> ' . $html_hold . '<p align="center">';
502 if ($this->query_result)
504 if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query))
506 $sql_report .= "Affected rows: <b>" . $this->sql_affectedrows($this->query_result) . '</b> | ';
508 $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $curtime) . 's</b>';
512 $error = $this->sql_error();
513 $sql_report .= '<b style="color: red">FAILED</b> - ' . SQL_LAYER . ' Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']);
516 $sql_report .= '</p>';
518 $this->sql_time += $endtime - $curtime;