5
* @version $Id: dbal.php,v 1.70 2007/12/06 12:27:53 acydburn Exp $
6
* @copyright (c) 2005 phpBB Group
7
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
14
if (!defined('IN_PHPBB'))
20
* Database Abstraction Layer
27
var $return_on_error = false;
28
var $transaction = false;
30
var $num_queries = array();
31
var $open_queries = array();
38
var $persistency = false;
43
// Set to true if error triggered
44
var $sql_error_triggered = false;
46
// Holding the last sql query on sql error
47
var $sql_error_sql = '';
49
// Holding transaction count
50
var $transactions = 0;
52
// Supports multi inserts?
53
var $multi_insert = false;
61
* Wildcards for matching any (%) or exactly one (_) character within LIKE expressions
71
$this->num_queries = array(
77
// Fill default sql layer based on the class being called.
78
// This can be changed by the specified layer itself later if needed.
79
$this->sql_layer = substr(get_class($this), 5);
81
// Do not change this please! This variable is used to easy the use of it - and is hardcoded.
82
$this->any_char = chr(0) . '%';
83
$this->one_char = chr(0) . '_';
87
* return on error or display error message
89
function sql_return_on_error($fail = false)
91
$this->sql_error_triggered = false;
92
$this->sql_error_sql = '';
94
$this->return_on_error = $fail;
98
* Return number of sql queries and cached sql queries used
100
function sql_num_queries($cached = false)
102
return ($cached) ? $this->num_queries['cached'] : $this->num_queries['normal'];
108
function sql_add_num_queries($cached = false)
110
$this->num_queries['cached'] += ($cached !== false) ? 1 : 0;
111
$this->num_queries['normal'] += ($cached !== false) ? 0 : 1;
112
$this->num_queries['total'] += 1;
116
* DBAL garbage collection, close sql connection
120
if (!$this->db_connect_id)
125
if ($this->transaction)
129
$this->sql_transaction('commit');
131
while ($this->transaction);
134
foreach ($this->open_queries as $query_id)
136
$this->sql_freeresult($query_id);
139
return $this->_sql_close();
144
* Doing some validation here.
146
function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
153
// Never use a negative total or offset
154
$total = ($total < 0) ? 0 : $total;
155
$offset = ($offset < 0) ? 0 : $offset;
157
return $this->_sql_query_limit($query, $total, $offset, $cache_ttl);
163
function sql_fetchrowset($query_id = false)
165
if ($query_id === false)
167
$query_id = $this->query_result;
170
if ($query_id !== false)
173
while ($row = $this->sql_fetchrow($query_id))
186
* if rownum is false, the current row is used, else it is pointing to the row (zero-based)
188
function sql_fetchfield($field, $rownum = false, $query_id = false)
192
if ($query_id === false)
194
$query_id = $this->query_result;
197
if ($query_id !== false)
199
if ($rownum !== false)
201
$this->sql_rowseek($rownum, $query_id);
204
if (!is_object($query_id) && isset($cache->sql_rowset[$query_id]))
206
return $cache->sql_fetchfield($query_id, $field);
209
$row = $this->sql_fetchrow($query_id);
210
return (isset($row[$field])) ? $row[$field] : false;
217
* Correctly adjust LIKE expression for special characters
218
* Some DBMS are handling them in a different way
220
* @param string $expression The expression to use. Every wildcard is escaped, except $this->any_char and $this->one_char
221
* @return string LIKE expression including the keyword!
223
function sql_like_expression($expression)
225
$expression = str_replace(array('_', '%'), array("\_", "\%"), $expression);
226
$expression = str_replace(array(chr(0) . "\_", chr(0) . "\%"), array('_', '%'), $expression);
228
return $this->_sql_like_expression('LIKE \'' . $this->sql_escape($expression) . '\'');
235
function sql_transaction($status = 'begin')
240
// If we are within a transaction we will not open another one, but enclose the current one to not loose data (prevening auto commit)
241
if ($this->transaction)
243
$this->transactions++;
247
$result = $this->_sql_transaction('begin');
254
$this->transaction = true;
258
// If there was a previously opened transaction we do not commit yet... but count back the number of inner transactions
259
if ($this->transaction && $this->transactions)
261
$this->transactions--;
265
$result = $this->_sql_transaction('commit');
272
$this->transaction = false;
273
$this->transactions = 0;
277
$result = $this->_sql_transaction('rollback');
278
$this->transaction = false;
279
$this->transactions = 0;
283
$result = $this->_sql_transaction($status);
291
* Build sql statement from array for insert/update/select statements
293
* Idea for this from Ikonboard
294
* Possible query values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT
297
function sql_build_array($query, $assoc_ary = false)
299
if (!is_array($assoc_ary))
304
$fields = $values = array();
306
if ($query == 'INSERT' || $query == 'INSERT_SELECT')
308
foreach ($assoc_ary as $key => $var)
312
if (is_array($var) && is_string($var[0]))
314
// This is used for INSERT_SELECT(s)
319
$values[] = $this->_sql_validate_value($var);
323
$query = ($query == 'INSERT') ? ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')' : ' (' . implode(', ', $fields) . ') SELECT ' . implode(', ', $values) . ' ';
325
else if ($query == 'MULTI_INSERT')
328
foreach ($assoc_ary as $id => $sql_ary)
330
// If by accident the sql array is only one-dimensional we build a normal insert statement
331
if (!is_array($sql_ary))
333
return $this->sql_build_array('INSERT', $assoc_ary);
337
foreach ($sql_ary as $key => $var)
339
$values[] = $this->_sql_validate_value($var);
341
$ary[] = '(' . implode(', ', $values) . ')';
344
$query = ' (' . implode(', ', array_keys($assoc_ary[0])) . ') VALUES ' . implode(', ', $ary);
346
else if ($query == 'UPDATE' || $query == 'SELECT')
349
foreach ($assoc_ary as $key => $var)
351
$values[] = "$key = " . $this->_sql_validate_value($var);
353
$query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
360
* Build IN or NOT IN sql comparison string, uses <> or = on single element
361
* arrays to improve comparison speed
364
* @param string $field name of the sql column that shall be compared
365
* @param array $array array of values that are allowed (IN) or not allowed (NOT IN)
366
* @param bool $negate true for NOT IN (), false for IN () (default)
367
* @param bool $allow_empty_set If true, allow $array to be empty, this function will return 1=1 or 1=0 then. Default to false.
369
function sql_in_set($field, $array, $negate = false, $allow_empty_set = false)
373
if (!$allow_empty_set)
375
// Print the backtrace to help identifying the location of the problematic code
376
$this->sql_error('No values specified for SQL IN comparison');
380
// NOT IN () actually means everything so use a tautology
385
// IN () actually means nothing so use a contradiction
393
if (!is_array($array))
395
$array = array($array);
398
if (sizeof($array) == 1)
401
$var = current($array);
403
return $field . ($negate ? ' <> ' : ' = ') . $this->_sql_validate_value($var);
407
return $field . ($negate ? ' NOT IN ' : ' IN ') . '(' . implode(', ', array_map(array($this, '_sql_validate_value'), $array)) . ')';
412
* Run more than one insert statement.
414
* @param string $table table name to run the statements on
415
* @param array &$sql_ary multi-dimensional array holding the statement data.
417
* @return bool false if no statements were executed.
420
function sql_multi_insert($table, &$sql_ary)
422
if (!sizeof($sql_ary))
427
if ($this->multi_insert)
429
$this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('MULTI_INSERT', $sql_ary));
433
foreach ($sql_ary as $ary)
440
$this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('INSERT', $ary));
448
* Function for validating values
451
function _sql_validate_value($var)
457
else if (is_string($var))
459
return "'" . $this->sql_escape($var) . "'";
463
return (is_bool($var)) ? intval($var) : $var;
468
* Build sql statement from array for select and select distinct statements
470
* Possible query values: SELECT, SELECT_DISTINCT
472
function sql_build_query($query, $array)
478
case 'SELECT_DISTINCT';
480
$sql = str_replace('_', ' ', $query) . ' ' . $array['SELECT'] . ' FROM ';
482
$table_array = array();
483
foreach ($array['FROM'] as $table_name => $alias)
485
if (is_array($alias))
487
foreach ($alias as $multi_alias)
489
$table_array[] = $table_name . ' ' . $multi_alias;
494
$table_array[] = $table_name . ' ' . $alias;
498
$sql .= $this->_sql_custom_build('FROM', implode(', ', $table_array));
500
if (!empty($array['LEFT_JOIN']))
502
foreach ($array['LEFT_JOIN'] as $join)
504
$sql .= ' LEFT JOIN ' . key($join['FROM']) . ' ' . current($join['FROM']) . ' ON (' . $join['ON'] . ')';
508
if (!empty($array['WHERE']))
510
$sql .= ' WHERE ' . $this->_sql_custom_build('WHERE', $array['WHERE']);
513
if (!empty($array['GROUP_BY']))
515
$sql .= ' GROUP BY ' . $array['GROUP_BY'];
518
if (!empty($array['ORDER_BY']))
520
$sql .= ' ORDER BY ' . $array['ORDER_BY'];
530
* display sql error page
532
function sql_error($sql = '')
534
global $auth, $user, $config;
536
// Set var to retrieve errored status
537
$this->sql_error_triggered = true;
538
$this->sql_error_sql = $sql;
540
$error = $this->_sql_error();
542
if (!$this->return_on_error)
544
$message = 'SQL ERROR [ ' . $this->sql_layer . ' ]<br /><br />' . $error['message'] . ' [' . $error['code'] . ']';
546
// Show complete SQL error and path to administrators only
547
// Additionally show complete error on installation or if extended debug mode is enabled
548
// The DEBUG_EXTRA constant is for development only!
549
if ((isset($auth) && $auth->acl_get('a_')) || defined('IN_INSTALL') || defined('DEBUG_EXTRA'))
551
// Print out a nice backtrace...
552
$backtrace = get_backtrace();
554
$message .= ($sql) ? '<br /><br />SQL<br /><br />' . htmlspecialchars($sql) : '';
555
$message .= ($backtrace) ? '<br /><br />BACKTRACE<br />' . $backtrace : '';
556
$message .= '<br />';
560
// If error occurs in initiating the session we need to use a pre-defined language string
561
// This could happen if the connection could not be established for example (then we are not able to grab the default language)
562
if (!isset($user->lang['SQL_ERROR_OCCURRED']))
564
$message .= '<br /><br />An sql error occurred while fetching this page. Please contact an administrator if this problem persists.';
568
if (!empty($config['board_contact']))
570
$message .= '<br /><br />' . sprintf($user->lang['SQL_ERROR_OCCURRED'], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
574
$message .= '<br /><br />' . sprintf($user->lang['SQL_ERROR_OCCURRED'], '', '');
579
if ($this->transaction)
581
$this->sql_transaction('rollback');
584
if (strlen($message) > 1024)
586
// We need to define $msg_long_text here to circumvent text stripping.
587
global $msg_long_text;
588
$msg_long_text = $message;
590
trigger_error(false, E_USER_ERROR);
593
trigger_error($message, E_USER_ERROR);
596
if ($this->transaction)
598
$this->sql_transaction('rollback');
607
function sql_report($mode, $query = '')
609
global $cache, $starttime, $phpbb_root_path, $user;
611
if (empty($_REQUEST['explain']))
616
if (!$query && $this->query_hold != '')
618
$query = $this->query_hold;
630
$mtime = explode(' ', microtime());
631
$totaltime = $mtime[0] + $mtime[1] - $starttime;
633
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
634
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
636
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
637
<meta http-equiv="Content-Style-Type" content="text/css" />
638
<meta http-equiv="imagetoolbar" content="no" />
639
<title>SQL Report</title>
640
<link href="' . $phpbb_root_path . 'adm/style/admin.css" rel="stylesheet" type="text/css" media="screen" />
642
<body id="errorpage">
644
<div id="page-header">
645
<a href="' . build_url('explain') . '">Return to previous page</a>
650
<span class="corners-top"><span></span></span>
654
<p><b>Page generated in ' . round($totaltime, 4) . " seconds with {$this->num_queries['normal']} queries" . (($this->num_queries['cached']) ? " + {$this->num_queries['cached']} " . (($this->num_queries['cached'] == 1) ? 'query' : 'queries') . ' returning data from cache' : '') . '</b></p>
656
<p>Time spent on ' . $this->sql_layer . ' queries: <b>' . round($this->sql_time, 5) . 's</b> | Time spent on PHP: <b>' . round($totaltime - $this->sql_time, 5) . 's</b></p>
659
' . $this->sql_report . '
661
<span class="corners-bottom"><span></span></span>
665
<div id="page-footer">
666
Powered by phpBB © 2000, 2002, 2005, 2007 <a href="http://www.phpbb.com/">phpBB Group</a>
677
$endtime = explode(' ', microtime());
678
$endtime = $endtime[0] + $endtime[1];
680
$this->sql_report .= '
682
<table cellspacing="1">
685
<th>Query #' . $this->num_queries['total'] . '</th>
690
<td class="row3"><textarea style="font-family:\'Courier New\',monospace;width:99%" rows="5" cols="10">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td>
695
' . $this->html_hold . '
697
<p style="text-align: center;">
700
if ($this->query_result)
702
if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query))
704
$this->sql_report .= 'Affected rows: <b>' . $this->sql_affectedrows($this->query_result) . '</b> | ';
706
$this->sql_report .= 'Before: ' . sprintf('%.5f', $this->curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $this->curtime) . 's</b>';
710
$error = $this->sql_error();
711
$this->sql_report .= '<b style="color: red">FAILED</b> - ' . $this->sql_layer . ' Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']);
714
$this->sql_report .= '</p><br /><br />';
716
$this->sql_time += $endtime - $this->curtime;
720
$this->query_hold = $query;
721
$this->html_hold = '';
723
$this->_sql_report($mode, $query);
725
$this->curtime = explode(' ', microtime());
726
$this->curtime = $this->curtime[0] + $this->curtime[1];
730
case 'add_select_row':
732
$html_table = func_get_arg(2);
733
$row = func_get_arg(3);
735
if (!$html_table && sizeof($row))
738
$this->html_hold .= '<table cellspacing="1"><tr>';
740
foreach (array_keys($row) as $val)
742
$this->html_hold .= '<th>' . (($val) ? ucwords(str_replace('_', ' ', $val)) : ' ') . '</th>';
744
$this->html_hold .= '</tr>';
746
$this->html_hold .= '<tr>';
749
foreach (array_values($row) as $val)
751
$class = ($class == 'row1') ? 'row2' : 'row1';
752
$this->html_hold .= '<td class="' . $class . '">' . (($val) ? $val : ' ') . '</td>';
754
$this->html_hold .= '</tr>';
762
$this->_sql_report($mode, $query);
766
case 'record_fromcache':
768
$endtime = func_get_arg(2);
769
$splittime = func_get_arg(3);
771
$time_cache = $endtime - $this->curtime;
772
$time_db = $splittime - $endtime;
773
$color = ($time_db > $time_cache) ? 'green' : 'red';
775
$this->sql_report .= '<table cellspacing="1"><thead><tr><th>Query results obtained from the cache</th></tr></thead><tbody><tr>';
776
$this->sql_report .= '<td class="row3"><textarea style="font-family:\'Courier New\',monospace;width:99%" rows="5" cols="10">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></tbody></table>';
777
$this->sql_report .= '<p style="text-align: center;">';
778
$this->sql_report .= 'Before: ' . sprintf('%.5f', $this->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><br /><br />';
780
// Pad the start time to not interfere with page timing
781
$starttime += $time_db;
787
$this->_sql_report($mode, $query);
797
* This variable holds the class name to use later
799
$sql_db = (!empty($dbms)) ? 'dbal_' . basename($dbms) : 'dbal';
b'\\ No newline at end of file'