5 * @version $Id: mssql.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', 'mssql');
21 * MSSQL Database Abstraction Layer
22 * Minimum Requirement is MSSQL 2000+
28 var $return_on_error = false;
29 var $transaction = false;
32 var $open_queries = array();
34 function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false)
36 $this->persistency = $persistency;
37 $this->user = $sqluser;
38 $this->server = $sqlserver . (($port) ? ':' . $port : '');
39 $this->dbname = $database;
41 $this->db_connect_id = ($this->persistency) ? @mssql_pconnect($this->server, $this->user, $sqlpassword) : @mssql_connect($this->server, $this->user, $sqlpassword);
43 if ($this->db_connect_id && $this->dbname != '')
45 if (!@mssql_select_db($this->dbname, $this->db_connect_id))
47 @mssql_close($this->db_connect_id);
52 return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
57 if (!$this->db_connect_id)
62 if ($this->transaction)
64 @mssql_query('COMMIT', $this->db_connect_id);
67 if (sizeof($this->open_queries))
69 foreach ($this->open_queries as $i_query_id => $query_id)
71 @mssql_free_result($query_id);
75 return @mssql_close($this->db_connect_id);
78 function sql_return_on_error($fail = false)
80 $this->return_on_error = $fail;
83 function sql_num_queries()
85 return $this->num_queries;
88 function sql_transaction($status = 'begin')
93 $result = @mssql_query('BEGIN TRANSACTION', $this->db_connect_id);
94 $this->transaction = true;
98 $result = @mssql_query('commit', $this->db_connect_id);
99 $this->transaction = false;
103 @mssql_query('ROLLBACK', $this->db_connect_id);
108 $result = @mssql_query('ROLLBACK', $this->db_connect_id);
109 $this->transaction = false;
120 function sql_query($query = '', $cache_ttl = 0)
126 // EXPLAIN only in extra debug mode
127 if (defined('DEBUG_EXTRA'))
129 $this->sql_report('start', $query);
132 $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
134 if (!$this->query_result)
136 $this->num_queries++;
138 if (($this->query_result = @mssql_query($query, $this->db_connect_id)) === false)
140 $this->sql_error($query);
143 if (defined('DEBUG_EXTRA'))
145 $this->sql_report('stop', $query);
148 if ($cache_ttl && method_exists($cache, 'sql_save'))
150 $this->open_queries[(int) $this->query_result] = $this->query_result;
151 $cache->sql_save($query, $this->query_result, $cache_ttl);
152 // sql_freeresult called within sql_save()
154 else if (strpos($query, 'SELECT') !== false && $this->query_result)
156 $this->open_queries[(int) $this->query_result] = $this->query_result;
159 else if (defined('DEBUG_EXTRA'))
161 $this->sql_report('fromcache', $query);
169 return ($this->query_result) ? $this->query_result : false;
172 function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
176 $this->query_result = false;
178 // if $total is set to 0 we do not want to limit the number of rows
184 $row_offset = ($total) ? $offset : '';
185 $num_rows = ($total) ? $total : $offset;
187 $query = 'SELECT TOP ' . ($row_offset + $num_rows) . ' ' . substr($query, 6);
189 return $this->sql_query($query, $cache_ttl);
197 // Idea for this from Ikonboard
198 function sql_build_array($query, $assoc_ary = false)
200 if (!is_array($assoc_ary))
207 if ($query == 'INSERT')
209 foreach ($assoc_ary as $key => $var)
217 elseif (is_string($var))
219 $values[] = "'" . $this->sql_escape($var) . "'";
223 $values[] = (is_bool($var)) ? intval($var) : $var;
227 $query = ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
229 else if ($query == 'UPDATE' || $query == 'SELECT')
232 foreach ($assoc_ary as $key => $var)
236 $values[] = "$key = NULL";
238 elseif (is_string($var))
240 $values[] = "$key = '" . $this->sql_escape($var) . "'";
244 $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var";
247 $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
253 // Other query methods
255 // NOTE :: Want to remove _ALL_ reliance on sql_numrows from core code ...
256 // don't want this here by a middle Milestone
257 function sql_numrows($query_id = false)
261 $query_id = $this->query_result;
264 // return (isset($this->limit_offset[$query_id])) ? @mssql_num_rows($query_id) - $this->limit_offset[$query_id] : @mssql_num_rows($query_id);
265 return ($query_id) ? @mssql_num_rows($query_id) : false;
268 function sql_affectedrows()
270 return ($this->db_connect_id) ? @mssql_rows_affected($this->db_connect_id) : false;
273 function sql_fetchrow($query_id = false)
279 $query_id = $this->query_result;
282 if (isset($cache->sql_rowset[$query_id]))
284 return $cache->sql_fetchrow($query_id);
287 $row = @mssql_fetch_array($query_id, MSSQL_ASSOC);
291 foreach ($row as $key => $value)
293 $row[$key] = ($value === ' ') ? trim($value) : $value;
300 function sql_fetchrowset($query_id = false)
304 $query_id = $this->query_result;
309 unset($this->rowset[$query_id]);
310 unset($this->row[$query_id]);
313 while ($this->rowset[$query_id] = $this->sql_fetchrow($query_id))
315 $result[] = $this->rowset[$query_id];
323 function sql_fetchfield($field, $rownum = -1, $query_id = false)
327 $query_id = $this->query_result;
334 // (!empty($this->limit_offset[$query_id])) ? @mssql_data_seek($query_id, ($this->limit_offset[$query_id] + $rownum)) : @mssql_data_seek($query_id, $rownum);
335 @mssql_data_seek($query_id, $rownum);
336 $row = @mssql_fetch_array($query_id, MSSQL_ASSOC);
337 $result = isset($row[$field]) ? $row[$field] : false;
341 if (empty($this->row[$query_id]) && empty($this->rowset[$query_id]))
343 if ($this->sql_fetchrow($query_id))
345 $result = $this->row[$query_id][$field];
350 if ($this->rowset[$query_id])
352 $result = $this->rowset[$query_id][$field];
354 elseif ($this->row[$query_id])
356 $result = $this->row[$query_id][$field];
367 function sql_rowseek($rownum, $query_id = false)
371 $query_id = $this->query_result;
374 if (isset($this->current_row[$query_id]))
376 // (!empty($this->limit_offset[$query_id])) ? @mssql_data_seek($query_id, ($this->limit_offset[$query_id] + $rownum)) : @mssql_data_seek($query_id, $rownum);
377 @mssql_data_seek($query_id, $rownum);
384 function sql_nextid()
386 $result_id = @mssql_query('SELECT @@IDENTITY', $this->db_connect_id);
389 if (@mssql_fetch_array($result_id, MSSQL_ASSOC))
391 return @mssql_result($result_id, 1);
398 function sql_freeresult($query_id = false)
402 $query_id = $this->query_result;
405 if (isset($this->open_queries[$query_id]))
407 unset($this->open_queries[$query_id]);
408 unset($this->result_rowset[$query_id]);
410 return @mssql_free_result($query_id);
416 function sql_escape($msg)
418 return str_replace("'", "''", str_replace('\\', '\\\\', $msg));
421 function sql_error($sql = '')
423 if (!$this->return_on_error)
425 $this_page = (isset($_SERVER['PHP_SELF']) && !empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
426 $this_page .= '&' . ((isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : (isset($_ENV['QUERY_STRING']) ? $_ENV['QUERY_STRING'] : ''));
428 $message = '<u>SQL ERROR</u> [ ' . SQL_LAYER . ' ]<br /><br />' . @mssql_get_last_message() . '<br /><br /><u>CALLING PAGE</u><br /><br />' . htmlspecialchars($this_page) . (($sql != '') ? '<br /><br /><u>SQL</u><br /><br />' . $sql : '') . '<br />';
430 if ($this->transaction)
432 $this->sql_transaction('rollback');
435 trigger_error($message, E_USER_ERROR);
439 'message' => @mssql_get_last_message($this->db_connect_id),
446 function sql_report($mode, $query = '')
448 if (empty($_GET['explain']))
453 global $cache, $starttime, $phpbb_root_path;
454 static $curtime, $query_hold, $html_hold;
455 static $sql_report = '';
456 static $cache_num_queries = 0;
458 if (!$query && !empty($query_hold))
460 $query = $query_hold;
472 $mtime = explode(' ', microtime());
473 $totaltime = $mtime[0] + $mtime[1] - $starttime;
475 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";
476 echo 'th { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic3.gif\') }' . "\n";
477 echo 'td.cat { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic1.gif\') }' . "\n";
478 echo '</style><title>' . $msg_title . '</title></head><body>';
479 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>';
481 echo '</td></tr></table><br /></body></html>';
486 $query_hold = $query;
489 $curtime = explode(' ', microtime());
490 $curtime = $curtime[0] + $curtime[1];
494 $endtime = explode(' ', microtime());
495 $endtime = $endtime[0] + $endtime[1];
497 $result = @mssql_query($query, $this->db_connect_id);
498 while ($void = @mssql_fetch_array($result, MSSQL_ASSOC))
500 // Take the time spent on parsing rows into account
502 $splittime = explode(' ', microtime());
503 $splittime = $splittime[0] + $splittime[1];
505 $time_cache = $endtime - $curtime;
506 $time_db = $splittime - $endtime;
507 $color = ($time_db > $time_cache) ? 'green' : 'red';
509 $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">';
511 $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>';
513 // Pad the start time to not interfere with page timing
514 $starttime += $time_db;
516 @mssql_free_result($result);
517 $cache_num_queries++;
521 $endtime = explode(' ', microtime());
522 $endtime = $endtime[0] + $endtime[1];
524 $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">';
526 if ($this->query_result)
528 if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query))
530 $sql_report .= "Affected rows: <b>" . $this->sql_affectedrows($this->query_result) . '</b> | ';
532 $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $curtime) . 's</b>';
536 $error = $this->sql_error();
537 $sql_report .= '<b style="color: red">FAILED</b> - ' . SQL_LAYER . ' Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']);
540 $sql_report .= '</p>';
542 $this->sql_time += $endtime - $curtime;