punbb/include/dblayer/pgsql.php
changeset 7 98bbc533541c
equal deleted inserted replaced
6:5e1f1e916419 7:98bbc533541c
       
     1 <?php
       
     2 /***********************************************************************
       
     3 
       
     4   Copyright (C) 2002-2008  PunBB.org
       
     5 
       
     6   This file is part of PunBB.
       
     7 
       
     8   PunBB is free software; you can redistribute it and/or modify it
       
     9   under the terms of the GNU General Public License as published
       
    10   by the Free Software Foundation; either version 2 of the License,
       
    11   or (at your option) any later version.
       
    12 
       
    13   PunBB is distributed in the hope that it will be useful, but
       
    14   WITHOUT ANY WARRANTY; without even the implied warranty of
       
    15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       
    16   GNU General Public License for more details.
       
    17 
       
    18   You should have received a copy of the GNU General Public License
       
    19   along with this program; if not, write to the Free Software
       
    20   Foundation, Inc., 59 Temple Place, Suite 330, Boston,
       
    21   MA  02111-1307  USA
       
    22 
       
    23 ************************************************************************/
       
    24 
       
    25 
       
    26 // Make sure we have built in support for PostgreSQL
       
    27 if (!function_exists('pg_connect'))
       
    28 	exit('This PHP environment doesn\'t have PostgreSQL support built in. PostgreSQL support is required if you want to use a PostgreSQL database to run this forum. Consult the PHP documentation for further assistance.');
       
    29 
       
    30 
       
    31 class DBLayer
       
    32 {
       
    33 	var $prefix;
       
    34 	var $link_id;
       
    35 	var $query_result;
       
    36 	var $last_query_text = array();
       
    37 	var $in_transaction = 0;
       
    38 
       
    39 	var $saved_queries = array();
       
    40 	var $num_queries = 0;
       
    41 
       
    42 	var $error_no = false;
       
    43 	var $error_msg = 'Unknown';
       
    44 
       
    45 
       
    46 	function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
       
    47 	{
       
    48 		$this->prefix = $db_prefix;
       
    49 
       
    50 		if ($db_host != '')
       
    51 		{
       
    52 			if (strpos($db_host, ':') !== false)
       
    53 			{
       
    54 				list($db_host, $dbport) = explode(':', $db_host);
       
    55 				$connect_str[] = 'host='.$db_host.' port='.$dbport;
       
    56 			}
       
    57 			else
       
    58 			{
       
    59 				if ($db_host != 'localhost')
       
    60 					$connect_str[] = 'host='.$db_host;
       
    61 			}
       
    62 		}
       
    63 
       
    64 		if ($db_name)
       
    65 			$connect_str[] = 'dbname='.$db_name;
       
    66 
       
    67 		if ($db_username != '')
       
    68 			$connect_str[] = 'user='.$db_username;
       
    69 
       
    70 		if ($db_password != '')
       
    71 			$connect_str[] = 'password='.$db_password;
       
    72 
       
    73 		if ($p_connect)
       
    74 			$this->link_id = @pg_pconnect(implode(' ', $connect_str));
       
    75 		else
       
    76 			$this->link_id = @pg_connect(implode(' ', $connect_str));
       
    77 
       
    78 		if (!$this->link_id)
       
    79 			error('Unable to connect to PostgreSQL server.', __FILE__, __LINE__);
       
    80 		else
       
    81 			return $this->link_id;
       
    82 	}
       
    83 
       
    84 
       
    85 	function start_transaction()
       
    86 	{
       
    87 		++$this->in_transaction;
       
    88 
       
    89 		return (@pg_query($this->link_id, 'BEGIN')) ? true : false;
       
    90 	}
       
    91 
       
    92 
       
    93 	function end_transaction()
       
    94 	{
       
    95 		--$this->in_transaction;
       
    96 
       
    97 		if (@pg_query($this->link_id, 'COMMIT'))
       
    98 			return true;
       
    99 		else
       
   100 		{
       
   101 			@pg_query($this->link_id, 'ROLLBACK');
       
   102 			return false;
       
   103 		}
       
   104 	}
       
   105 
       
   106 
       
   107 	function query($sql, $unbuffered = false)	// $unbuffered is ignored since there is no pgsql_unbuffered_query()
       
   108 	{
       
   109 		if (strlen($sql) > 140000)
       
   110 			exit('Insane query. Aborting.');
       
   111 
       
   112 		if (strrpos($sql, 'LIMIT') !== false)
       
   113 			$sql = preg_replace('#LIMIT ([0-9]+),([ 0-9]+)#', 'LIMIT \\2 OFFSET \\1', $sql);
       
   114 
       
   115 		if (defined('PUN_SHOW_QUERIES'))
       
   116 			$q_start = get_microtime();
       
   117 
       
   118 		@pg_send_query($this->link_id, $sql);
       
   119 		$this->query_result = @pg_get_result($this->link_id);
       
   120 
       
   121 		if (pg_result_status($this->query_result) != PGSQL_FATAL_ERROR)
       
   122 		{
       
   123 			if (defined('PUN_SHOW_QUERIES'))
       
   124 				$this->saved_queries[] = array($sql, sprintf('%.5f', get_microtime() - $q_start));
       
   125 
       
   126 			++$this->num_queries;
       
   127 
       
   128 			$this->last_query_text[$this->query_result] = $sql;
       
   129 
       
   130 			return $this->query_result;
       
   131 		}
       
   132 		else
       
   133 		{
       
   134 			if (defined('PUN_SHOW_QUERIES'))
       
   135 				$this->saved_queries[] = array($sql, 0);
       
   136 
       
   137 			$this->error_msg = @pg_result_error($this->query_result);
       
   138 
       
   139 			if ($this->in_transaction)
       
   140 				@pg_query($this->link_id, 'ROLLBACK');
       
   141 
       
   142 			--$this->in_transaction;
       
   143 
       
   144 			return false;
       
   145 		}
       
   146 	}
       
   147 
       
   148 
       
   149 	function query_build($query, $unbuffered = false)
       
   150 	{
       
   151 		$sql = '';
       
   152 
       
   153 		if (isset($query['SELECT']))
       
   154 		{
       
   155 			$sql = 'SELECT '.$query['SELECT'].' FROM '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['FROM'];
       
   156 
       
   157 			if (isset($query['JOINS']))
       
   158 			{
       
   159 				foreach ($query['JOINS'] as $cur_join)
       
   160 					$sql .= ' '.key($cur_join).' '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).current($cur_join).' ON '.$cur_join['ON'];
       
   161 			}
       
   162 
       
   163 			if (!empty($query['WHERE']))
       
   164 				$sql .= ' WHERE '.$query['WHERE'];
       
   165 			if (!empty($query['GROUP BY']))
       
   166 				$sql .= ' GROUP BY '.$query['GROUP BY'];
       
   167 			if (!empty($query['HAVING']))
       
   168 				$sql .= ' HAVING '.$query['HAVING'];
       
   169 			if (!empty($query['ORDER BY']))
       
   170 				$sql .= ' ORDER BY '.$query['ORDER BY'];
       
   171 			if (!empty($query['LIMIT']))
       
   172 				$sql .= ' LIMIT '.$query['LIMIT'];
       
   173 		}
       
   174 		else if (isset($query['INSERT']))
       
   175 		{
       
   176 			$sql = 'INSERT INTO '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['INTO'];
       
   177 
       
   178 			if (!empty($query['INSERT']))
       
   179 				$sql .= ' ('.$query['INSERT'].')';
       
   180 
       
   181 			$sql .= ' VALUES('.$query['VALUES'].')';
       
   182 		}
       
   183 		else if (isset($query['UPDATE']))
       
   184 		{
       
   185 			$query['UPDATE'] = (isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['UPDATE'];
       
   186 
       
   187 			$sql = 'UPDATE '.$query['UPDATE'].' SET '.$query['SET'];
       
   188 
       
   189 			if (!empty($query['WHERE']))
       
   190 				$sql .= ' WHERE '.$query['WHERE'];
       
   191 		}
       
   192 		else if (isset($query['DELETE']))
       
   193 		{
       
   194 			$sql = 'DELETE FROM '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['DELETE'];
       
   195 
       
   196 			if (!empty($query['WHERE']))
       
   197 				$sql .= ' WHERE '.$query['WHERE'];
       
   198 		}
       
   199 
       
   200 		return $this->query($sql, $unbuffered);
       
   201 	}
       
   202 
       
   203 
       
   204 	function result($query_id = 0, $row = 0)
       
   205 	{
       
   206 		return ($query_id) ? @pg_fetch_result($query_id, $row, 0) : false;
       
   207 	}
       
   208 
       
   209 
       
   210 	function fetch_assoc($query_id = 0)
       
   211 	{
       
   212 		return ($query_id) ? @pg_fetch_assoc($query_id) : false;
       
   213 	}
       
   214 
       
   215 
       
   216 	function fetch_row($query_id = 0)
       
   217 	{
       
   218 		return ($query_id) ? @pg_fetch_row($query_id) : false;
       
   219 	}
       
   220 
       
   221 
       
   222 	function num_rows($query_id = 0)
       
   223 	{
       
   224 		return ($query_id) ? @pg_num_rows($query_id) : false;
       
   225 	}
       
   226 
       
   227 
       
   228 	function affected_rows()
       
   229 	{
       
   230 		return ($this->query_result) ? @pg_affected_rows($this->query_result) : false;
       
   231 	}
       
   232 
       
   233 
       
   234 	function insert_id()
       
   235 	{
       
   236 		$query_id = $this->query_result;
       
   237 
       
   238 		if ($query_id && $this->last_query_text[$query_id] != '')
       
   239 		{
       
   240 			if (preg_match('/^INSERT INTO ([a-z0-9\_\-]+)/is', $this->last_query_text[$query_id], $table_name))
       
   241 			{
       
   242 				// Hack (don't ask)
       
   243 				if (substr($table_name[1], -6) == 'groups')
       
   244 					$table_name[1] .= '_g';
       
   245 
       
   246 				$temp_q_id = @pg_query($this->link_id, 'SELECT currval(\''.$table_name[1].'_id_seq\')');
       
   247 				return ($temp_q_id) ? intval(@pg_fetch_result($temp_q_id, 0)) : false;
       
   248 			}
       
   249 		}
       
   250 
       
   251 		return false;
       
   252 	}
       
   253 
       
   254 
       
   255 	function get_num_queries()
       
   256 	{
       
   257 		return $this->num_queries;
       
   258 	}
       
   259 
       
   260 
       
   261 	function get_saved_queries()
       
   262 	{
       
   263 		return $this->saved_queries;
       
   264 	}
       
   265 
       
   266 
       
   267 	function free_result($query_id = false)
       
   268 	{
       
   269 		if (!$query_id)
       
   270 			$query_id = $this->query_result;
       
   271 
       
   272 		return ($query_id) ? @pg_free_result($query_id) : false;
       
   273 	}
       
   274 
       
   275 
       
   276 	function escape($str)
       
   277 	{
       
   278 		return is_array($str) ? '' : pg_escape_string($str);
       
   279 	}
       
   280 
       
   281 
       
   282 	function error()
       
   283 	{
       
   284 		$result['error_sql'] = @current(@end($this->saved_queries));
       
   285 		$result['error_no'] = false;
       
   286 /*
       
   287 		if (!empty($this->query_result))
       
   288 		{
       
   289 			$result['error_msg'] = trim(@pg_result_error($this->query_result));
       
   290 			if ($result['error_msg'] != '')
       
   291 				return $result;
       
   292 		}
       
   293 
       
   294 		$result['error_msg'] = (!empty($this->link_id)) ? trim(@pg_last_error($this->link_id)) : trim(@pg_last_error());
       
   295 */
       
   296 		$result['error_msg'] = $this->error_msg;
       
   297 
       
   298 		return $result;
       
   299 	}
       
   300 
       
   301 
       
   302 	function close()
       
   303 	{
       
   304 		if ($this->link_id)
       
   305 		{
       
   306 			if ($this->in_transaction)
       
   307 			{
       
   308 				if (defined('PUN_SHOW_QUERIES'))
       
   309 					$this->saved_queries[] = array('COMMIT', 0);
       
   310 
       
   311 				@pg_query($this->link_id, 'COMMIT');
       
   312 			}
       
   313 
       
   314 			if ($this->query_result)
       
   315 				@pg_free_result($this->query_result);
       
   316 
       
   317 			return @pg_close($this->link_id);
       
   318 		}
       
   319 		else
       
   320 			return false;
       
   321 	}
       
   322 
       
   323 
       
   324 	function table_exists($table_name)
       
   325 	{
       
   326 		$result = $this->query('SELECT 1 FROM pg_class WHERE relname = \''.$this->escape($table_name).'\'');
       
   327 		return $this->num_rows($result) > 0;
       
   328 	}
       
   329 
       
   330 
       
   331 	function field_exists($table_name, $field_name)
       
   332 	{
       
   333 		$result = $this->query('SELECT 1 FROM pg_class c INNER JOIN pg_attribute a ON a.attrelid = c.oid WHERE c.relname = \''.$this->escape($table_name).'\' AND a.attname = \''.$this->escape($field_name).'\'');
       
   334 		return $this->num_rows($result) > 0;
       
   335 	}
       
   336 
       
   337 
       
   338 	function index_exists($table_name, $index_name)
       
   339 	{
       
   340 		$result = $this->query('SELECT 1 FROM pg_index i INNER JOIN pg_class c1 ON c1.oid = i.indrelid INNER JOIN pg_class c2 ON c2.oid = i.indexrelid WHERE c1.relname = \''.$this->escape($table_name).'\' AND c2.relname = \''.$this->escape($index_name).'\'');
       
   341 		return $this->num_rows($result) > 0;
       
   342 	}
       
   343 
       
   344 
       
   345 	function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null)
       
   346 	{
       
   347 		if ($this->field_exists($table_name, $field_name))
       
   348 			return;
       
   349 
       
   350 		$field_type = str_replace(array('TINY', 'FLOAT'), array('SMALL', 'REAL'), strtoupper($field_type));
       
   351 		$field_type = preg_replace('/(.*?INT)(\([0-9]+)\)/', '$1', $field_type);
       
   352 
       
   353 		$this->query('ALTER TABLE '.$table_name.' ADD '.$field_name.' '.$field_type) or error(__FILE__, __LINE__);
       
   354 
       
   355 		if ($default_value !== null)
       
   356 		{
       
   357 			if (!is_int($default_value) && !is_float($default_value))
       
   358 				$default_value = '\''.$this->escape($default_value).'\'';
       
   359 
       
   360 			$this->query('ALTER TABLE '.$table_name.' ALTER '.$field_name.' SET DEFAULT '.$default_value) or error(__FILE__, __LINE__);
       
   361 			$this->query('UPDATE '.$table_name.' SET '.$field_name.'='.$default_value) or error(__FILE__, __LINE__);
       
   362 		}
       
   363 
       
   364 		if (!$allow_null)
       
   365 			$this->query('ALTER TABLE '.$table_name.' ALTER '.$field_name.' SET NOT NULL') or error(__FILE__, __LINE__);
       
   366 	}
       
   367 
       
   368 
       
   369 	function drop_field($table_name, $field_name)
       
   370 	{
       
   371 		if (!$this->field_exists($table_name, $field_name))
       
   372 			return;
       
   373 
       
   374 		$this->query('ALTER TABLE '.$table_name.' DROP '.$field_name) or error(__FILE__, __LINE__);
       
   375 	}
       
   376 }