4 * @package dbal_postgres
5 * @version $Id: postgres.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', 'postgresql');
20 * @package dbal_postgres
21 * PostgreSQL Database Abstraction Layer
22 * Minimum Requirement is Version 7.3+
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->connect_string = '';
40 $this->connect_string .= "user=$sqluser ";
45 $this->connect_string .= "password=$sqlpassword ";
50 if (ereg(":", $sqlserver))
52 list($sqlserver, $sqlport) = split(":", $sqlserver);
53 $this->connect_string .= "host=$sqlserver port=$sqlport ";
57 if ($sqlserver != "localhost")
59 $this->connect_string .= "host=$sqlserver ";
64 $this->connect_string .= "port=$port ";
71 $this->dbname = $database;
72 $this->connect_string .= "dbname=$database";
75 $this->persistency = $persistency;
77 $this->db_connect_id = ($this->persistency) ? @pg_pconnect($this->connect_string) : @pg_connect($this->connect_string);
79 return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
87 if (!$this->db_connect_id)
92 if ($this->transaction)
94 @pg_exec($this->db_connect_id, 'COMMIT');
97 return @pg_close($this->db_connect_id);
100 function sql_return_on_error($fail = false)
102 $this->return_on_error = $fail;
105 function sql_num_queries()
107 return $this->num_queries;
110 function sql_transaction($status = 'begin')
115 $result = @pg_exec($this->db_connect_id, 'BEGIN');
116 $this->transaction = true;
120 $result = @pg_exec($this->db_connect_id, 'COMMIT');
121 $this->transaction = false;
125 @pg_exec($this->db_connect_id, 'ROLLBACK');
130 $result = @pg_exec($this->db_connect_id, 'ROLLBACK');
131 $this->transaction = false;
142 function sql_query($query = '', $cache_ttl = 0)
148 // EXPLAIN only in extra debug mode
149 if (defined('DEBUG_EXTRA'))
151 $this->sql_report('start', $query);
154 $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
156 if (!$this->query_result)
158 $this->num_queries++;
159 $this->last_query_text = $query;
161 if (($this->query_result = @pg_exec($this->db_connect_id, $query)) === false)
163 $this->sql_error($query);
166 if (defined('DEBUG_EXTRA'))
168 $this->sql_report('stop', $query);
171 if ($cache_ttl && method_exists($cache, 'sql_save'))
173 $cache->sql_save($query, $this->query_result, $cache_ttl);
176 else if (defined('DEBUG_EXTRA'))
178 $this->sql_report('fromcache', $query);
186 return ($this->query_result) ? $this->query_result : false;
189 function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
193 $this->query_result = false;
195 // if $total is set to 0 we do not want to limit the number of rows
201 $query .= "\n LIMIT $total OFFSET $offset";
203 return $this->sql_query($query, $cache_ttl);
211 // Idea for this from Ikonboard
212 function sql_build_array($query, $assoc_ary = false)
214 if (!is_array($assoc_ary))
221 if ($query == 'INSERT')
223 foreach ($assoc_ary as $key => $var)
231 elseif (is_string($var))
233 $values[] = "'" . $this->sql_escape($var) . "'";
237 $values[] = (is_bool($var)) ? intval($var) : $var;
241 $query = ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
243 else if ($query == 'UPDATE' || $query == 'SELECT')
246 foreach ($assoc_ary as $key => $var)
250 $values[] = "$key = NULL";
252 elseif (is_string($var))
254 $values[] = "$key = '" . $this->sql_escape($var) . "'";
258 $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var";
261 $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
267 // Other query methods
269 // NOTE :: Want to remove _ALL_ reliance on sql_numrows from core code ...
270 // don't want this here by a middle Milestone
271 function sql_numrows($query_id = false)
275 $query_id = $this->query_result;
278 return ($query_id) ? @pg_numrows($query_id) : false;
281 function sql_affectedrows($query_id = false)
285 $query_id = $this->query_result;
288 return ($query_id) ? @pg_cmdtuples($query_id) : false;
291 function sql_fetchrow($query_id = false)
297 $query_id = $this->query_result;
300 if (!isset($this->rownum[$query_id]))
302 $this->rownum[$query_id] = 0;
305 if (isset($cache->sql_rowset[$query_id]))
307 return $cache->sql_fetchrow($query_id);
310 $result = @pg_fetch_array($query_id, NULL, PGSQL_ASSOC);
314 $this->rownum[$query_id]++;
320 function sql_fetchrowset($query_id = false)
324 $query_id = $this->query_result;
331 unset($this->rowset[$query_id]);
332 unset($this->row[$query_id]);
335 while ($this->rowset[$query_id] = $this->sql_fetchrow($query_id))
337 $result[] = $this->rowset[$query_id];
345 function sql_fetchfield($field, $rownum = -1, $query_id = false)
349 $query_id = $this->query_result;
356 if (@function_exists('pg_result_seek'))
358 @pg_result_seek($query_id, $rownum);
359 $row = @pg_fetch_assoc($query_id);
360 $result = isset($row[$field]) ? $row[$field] : false;
364 $this->sql_rowseek($offset, $query_id);
365 $row = $this->sql_fetchrow($query_id);
366 $result = isset($row[$field]) ? $row[$field] : false;
371 if (empty($this->row[$query_id]) && empty($this->rowset[$query_id]))
373 if ($this->sql_fetchrow($query_id))
375 $result = $this->row[$query_id][$field];
380 if ($this->rowset[$query_id])
382 $result = $this->rowset[$query_id][$field];
384 elseif ($this->row[$query_id])
386 $result = $this->row[$query_id][$field];
395 function sql_rowseek($offset, $query_id = false)
399 $query_id = $this->query_result;
406 if (@function_exists('pg_result_seek'))
408 @pg_result_seek($query_id, $rownum);
412 for ($i = $this->rownum[$query_id]; $i < $offset; $i++)
414 $this->sql_fetchrow($query_id);
428 function sql_nextid()
430 $query_id = $this->query_result;
432 if ($query_id && $this->last_query_text != '')
434 if (preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $this->last_query_text, $tablename))
436 $query = "SELECT currval('" . $tablename[1] . "_id_seq') AS last_value";
437 $temp_q_id = @pg_exec($this->db_connect_id, $query);
443 $temp_result = @pg_fetch_array($temp_q_id, NULL, PGSQL_ASSOC);
445 return ($temp_result) ? $temp_result['last_value'] : false;
452 function sql_freeresult($query_id = false)
456 $query_id = $this->query_result;
459 return (is_resource($query_id)) ? @pg_freeresult($query_id) : false;
462 function sql_escape($msg)
464 return str_replace("'", "''", str_replace('\\', '\\\\', $msg));
467 function sql_error($sql = '')
469 if (!$this->return_on_error)
471 $this_page = (isset($_SERVER['PHP_SELF']) && !empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
472 $this_page .= '&' . ((isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : (isset($_ENV['QUERY_STRING']) ? $_ENV['QUERY_STRING'] : ''));
474 $message = '<u>SQL ERROR</u> [ ' . SQL_LAYER . ' ]<br /><br />' . @pg_errormessage() . '<br /><br /><u>CALLING PAGE</u><br /><br />' . htmlspecialchars($this_page) . (($sql != '') ? '<br /><br /><u>SQL</u><br /><br />' . $sql : '') . '<br />';
476 if ($this->transaction)
478 $this->sql_transaction('rollback');
481 trigger_error($message, E_USER_ERROR);
485 'message' => @pg_errormessage(),
492 function sql_report($mode, $query = '')
494 if (empty($_GET['explain']))
499 global $cache, $starttime, $phpbb_root_path;
500 static $curtime, $query_hold, $html_hold;
501 static $sql_report = '';
502 static $cache_num_queries = 0;
504 if (!$query && !empty($query_hold))
506 $query = $query_hold;
518 $mtime = explode(' ', microtime());
519 $totaltime = $mtime[0] + $mtime[1] - $starttime;
521 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";
522 echo 'th { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic3.gif\') }' . "\n";
523 echo 'td.cat { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic1.gif\') }' . "\n";
524 echo '</style><title>' . $msg_title . '</title></head><body>';
525 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>';
527 echo '</td></tr></table><br /></body></html>';
532 $query_hold = $query;
535 $curtime = explode(' ', microtime());
536 $curtime = $curtime[0] + $curtime[1];
540 $endtime = explode(' ', microtime());
541 $endtime = $endtime[0] + $endtime[1];
543 $result = @pg_exec($this->db_connect_id, $query);
544 while ($void = @pg_fetch_array($result, NULL, PGSQL_ASSOC))
546 // Take the time spent on parsing rows into account
548 $splittime = explode(' ', microtime());
549 $splittime = $splittime[0] + $splittime[1];
551 $time_cache = $endtime - $curtime;
552 $time_db = $splittime - $endtime;
553 $color = ($time_db > $time_cache) ? 'green' : 'red';
555 $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">';
557 $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>';
559 // Pad the start time to not interfere with page timing
560 $starttime += $time_db;
562 @pg_freeresult($result);
563 $cache_num_queries++;
567 $endtime = explode(' ', microtime());
568 $endtime = $endtime[0] + $endtime[1];
570 $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">';
572 if ($this->query_result)
574 if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query))
576 $sql_report .= "Affected rows: <b>" . $this->sql_affectedrows($this->query_result) . '</b> | ';
578 $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $curtime) . 's</b>';
582 $error = $this->sql_error();
583 $sql_report .= '<b style="color: red">FAILED</b> - ' . SQL_LAYER . ' Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']);
586 $sql_report .= '</p>';
588 $this->sql_time += $endtime - $curtime;
593 } // class ... db_sql