includes/db/mssqlnative.php
author indvdum (gotoindvdum[at]gmail[dot]com)
Sat, 10 Mar 2012 00:11:31 +0400
changeset 14 88d35b740f20
parent 0 ceef6d64c21d
permissions -rw-r--r--
HG ignore
     1 <?php
     2 /**
     3 *
     4 * @package dbal
     5 * @version $Id$
     6 * @copyright (c) 2010 phpBB Group
     7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
     8 *
     9 * This is the MS SQL Server Native database abstraction layer.
    10 * PHP mssql native driver required.
    11 * @author Chris Pucci
    12 *
    13 */
    14 
    15 /**
    16 * @ignore
    17 */
    18 if (!defined('IN_PHPBB'))
    19 {
    20 	exit;
    21 }
    22 
    23 include_once($phpbb_root_path . 'includes/db/dbal.' . $phpEx);
    24 
    25 /**
    26  * Prior to version 1.1 the SQL Server Native PHP driver didn't support sqlsrv_num_rows, or cursor based seeking so we recall all rows into an array
    27  * and maintain our own cursor index into that array.
    28  */
    29 class result_mssqlnative
    30 {
    31 	public function result_mssqlnative($queryresult = false)
    32 	{
    33 		$this->m_cursor = 0;
    34 		$this->m_rows = array();
    35 		$this->m_num_fields = sqlsrv_num_fields($queryresult);
    36 		$this->m_field_meta = sqlsrv_field_metadata($queryresult);
    37 
    38 		while ($row = sqlsrv_fetch_array($queryresult, SQLSRV_FETCH_ASSOC))
    39 		{
    40 			if ($row !== null)
    41 			{
    42 				foreach($row as $k => $v)
    43 				{
    44 					if (is_object($v) && method_exists($v, 'format'))
    45 					{
    46 						$row[$k] = $v->format("Y-m-d\TH:i:s\Z");
    47 					}
    48 				}
    49 				$this->m_rows[] = $row;//read results into memory, cursors are not supported
    50 			}
    51 		}
    52 
    53 		$this->m_row_count = sizeof($this->m_rows);
    54 	}
    55 
    56 	private function array_to_obj($array, &$obj)
    57 	{
    58 		foreach ($array as $key => $value)
    59 		{
    60 			if (is_array($value))
    61 			{
    62 				$obj->$key = new stdClass();
    63 				array_to_obj($value, $obj->$key);
    64 			}
    65 			else
    66 			{
    67 				$obj->$key = $value;
    68 			}
    69 		}
    70 		return $obj;
    71 	}
    72 
    73 	public function fetch($mode = SQLSRV_FETCH_BOTH, $object_class = 'stdClass')
    74 	{
    75 		if ($this->m_cursor >= $this->m_row_count || $this->m_row_count == 0)
    76 		{
    77 			return false;
    78 		}
    79 
    80 		$ret = false;
    81 		$arr_num = array();
    82 
    83 		if ($mode == SQLSRV_FETCH_NUMERIC || $mode == SQLSRV_FETCH_BOTH)
    84 		{
    85 			foreach($this->m_rows[$this->m_cursor] as $key => $value)
    86 			{
    87 				$arr_num[] = $value;
    88 			}
    89 		}
    90 
    91 		switch ($mode)
    92 		{
    93 			case SQLSRV_FETCH_ASSOC:
    94 				$ret = $this->m_rows[$this->m_cursor];
    95 			break;
    96 			case SQLSRV_FETCH_NUMERIC:
    97 				$ret = $arr_num;
    98 			break;
    99 			case 'OBJECT':
   100 				$ret = $this->array_to_obj($this->m_rows[$this->m_cursor], $o = new $object_class);
   101 			break;
   102 			case SQLSRV_FETCH_BOTH:
   103 			default:
   104 				$ret = $this->m_rows[$this->m_cursor] + $arr_num;
   105 			break;
   106 		}
   107 		$this->m_cursor++;
   108 		return $ret;
   109 	}
   110 
   111 	public function get($pos, $fld)
   112 	{
   113 		return $this->m_rows[$pos][$fld];
   114 	}
   115 
   116 	public function num_rows()
   117 	{
   118 		return $this->m_row_count;
   119 	}
   120 
   121 	public function seek($iRow)
   122 	{
   123 		$this->m_cursor = min($iRow, $this->m_row_count);
   124 	}
   125 
   126 	public function num_fields()
   127 	{
   128 		return $this->m_num_fields;
   129 	}
   130 
   131 	public function field_name($nr)
   132 	{
   133 		$arr_keys = array_keys($this->m_rows[0]);
   134 		return $arr_keys[$nr];
   135 	}
   136 
   137 	public function field_type($nr)
   138 	{
   139 		$i = 0;
   140 		$int_type = -1;
   141 		$str_type = '';
   142 
   143 		foreach ($this->m_field_meta as $meta)
   144 		{
   145 			if ($nr == $i)
   146 			{
   147 				$int_type = $meta['Type'];
   148 				break;
   149 			}
   150 			$i++;
   151 		}
   152 
   153 		//http://msdn.microsoft.com/en-us/library/cc296183.aspx contains type table
   154 		switch ($int_type)
   155 		{
   156 			case SQLSRV_SQLTYPE_BIGINT: 		$str_type = 'bigint'; break;
   157 			case SQLSRV_SQLTYPE_BINARY: 		$str_type = 'binary'; break;
   158 			case SQLSRV_SQLTYPE_BIT: 			$str_type = 'bit'; break;
   159 			case SQLSRV_SQLTYPE_CHAR: 			$str_type = 'char'; break;
   160 			case SQLSRV_SQLTYPE_DATETIME: 		$str_type = 'datetime'; break;
   161 			case SQLSRV_SQLTYPE_DECIMAL/*($precision, $scale)*/: $str_type = 'decimal'; break;
   162 			case SQLSRV_SQLTYPE_FLOAT: 			$str_type = 'float'; break;
   163 			case SQLSRV_SQLTYPE_IMAGE: 			$str_type = 'image'; break;
   164 			case SQLSRV_SQLTYPE_INT: 			$str_type = 'int'; break;
   165 			case SQLSRV_SQLTYPE_MONEY: 			$str_type = 'money'; break;
   166 			case SQLSRV_SQLTYPE_NCHAR/*($charCount)*/: $str_type = 'nchar'; break;
   167 			case SQLSRV_SQLTYPE_NUMERIC/*($precision, $scale)*/: $str_type = 'numeric'; break;
   168 			case SQLSRV_SQLTYPE_NVARCHAR/*($charCount)*/: $str_type = 'nvarchar'; break;
   169 			case SQLSRV_SQLTYPE_NTEXT: 			$str_type = 'ntext'; break;
   170 			case SQLSRV_SQLTYPE_REAL: 			$str_type = 'real'; break;
   171 			case SQLSRV_SQLTYPE_SMALLDATETIME: 	$str_type = 'smalldatetime'; break;
   172 			case SQLSRV_SQLTYPE_SMALLINT: 		$str_type = 'smallint'; break;
   173 			case SQLSRV_SQLTYPE_SMALLMONEY: 	$str_type = 'smallmoney'; break;
   174 			case SQLSRV_SQLTYPE_TEXT: 			$str_type = 'text'; break;
   175 			case SQLSRV_SQLTYPE_TIMESTAMP: 		$str_type = 'timestamp'; break;
   176 			case SQLSRV_SQLTYPE_TINYINT: 		$str_type = 'tinyint'; break;
   177 			case SQLSRV_SQLTYPE_UNIQUEIDENTIFIER: $str_type = 'uniqueidentifier'; break;
   178 			case SQLSRV_SQLTYPE_UDT: 			$str_type = 'UDT'; break;
   179 			case SQLSRV_SQLTYPE_VARBINARY/*($byteCount)*/: $str_type = 'varbinary'; break;
   180 			case SQLSRV_SQLTYPE_VARCHAR/*($charCount)*/: $str_type = 'varchar'; break;
   181 			case SQLSRV_SQLTYPE_XML: 			$str_type = 'xml'; break;
   182 			default: $str_type = $int_type;
   183 		}
   184 		return $str_type;
   185 	}
   186 
   187 	public function free()
   188 	{
   189 		unset($this->m_rows);
   190 		return;
   191 	}
   192 }
   193 
   194 /**
   195 * @package dbal
   196 */
   197 class dbal_mssqlnative extends dbal
   198 {
   199 	var $m_insert_id = NULL;
   200 	var $last_query_text = '';
   201 	var $query_options = array();
   202 
   203 	/**
   204 	* Connect to server
   205 	*/
   206 	function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
   207 	{
   208 		# Test for driver support, to avoid suppressed fatal error
   209 		if (!function_exists('sqlsrv_connect'))
   210 		{
   211 			trigger_error('Native MS SQL Server driver for PHP is missing or needs to be updated. Version 1.1 or later is required to install phpBB3. You can download the driver from: http://www.microsoft.com/sqlserver/2005/en/us/PHP-Driver.aspx\n', E_USER_ERROR);
   212 		}
   213 
   214 		//set up connection variables
   215 		$this->persistency = $persistency;
   216 		$this->user = $sqluser;
   217 		$this->dbname = $database;
   218 		$port_delimiter = (defined('PHP_OS') && substr(PHP_OS, 0, 3) === 'WIN') ? ',' : ':';
   219 		$this->server = $sqlserver . (($port) ? $port_delimiter . $port : '');
   220 
   221 		//connect to database
   222 		error_reporting(E_ALL);
   223 		$this->db_connect_id = sqlsrv_connect($this->server, array(
   224 			'Database' => $this->dbname,
   225 			'UID' => $this->user,
   226 			'PWD' => $sqlpassword
   227 		));
   228 
   229 		return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
   230 	}
   231 
   232 	/**
   233 	* Version information about used database
   234 	* @param bool $raw if true, only return the fetched sql_server_version
   235 	* @param bool $use_cache If true, it is safe to retrieve the value from the cache
   236 	* @return string sql server version
   237 	*/
   238 	function sql_server_info($raw = false, $use_cache = true)
   239 	{
   240 		global $cache;
   241 
   242 		if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mssql_version')) === false)
   243 		{
   244 			$arr_server_info = sqlsrv_server_info($this->db_connect_id);
   245 			$this->sql_server_version = $arr_server_info['SQLServerVersion'];
   246 
   247 			if (!empty($cache) && $use_cache)
   248 			{
   249 				$cache->put('mssql_version', $this->sql_server_version);
   250 			}
   251 		}
   252 
   253 		if ($raw)
   254 		{
   255 			return $this->sql_server_version;
   256 		}
   257 
   258 		return ($this->sql_server_version) ? 'MSSQL<br />' . $this->sql_server_version : 'MSSQL';
   259 	}
   260 
   261 	/**
   262 	* {@inheritDoc}
   263 	*/
   264 	function sql_buffer_nested_transactions()
   265 	{
   266 		return true;
   267 	}
   268 
   269 	/**
   270 	* SQL Transaction
   271 	* @access private
   272 	*/
   273 	function _sql_transaction($status = 'begin')
   274 	{
   275 		switch ($status)
   276 		{
   277 			case 'begin':
   278 				return sqlsrv_begin_transaction($this->db_connect_id);
   279 			break;
   280 
   281 			case 'commit':
   282 				return sqlsrv_commit($this->db_connect_id);
   283 			break;
   284 
   285 			case 'rollback':
   286 				return sqlsrv_rollback($this->db_connect_id);
   287 			break;
   288 		}
   289 		return true;
   290 	}
   291 
   292 	/**
   293 	* Base query method
   294 	*
   295 	* @param	string	$query		Contains the SQL query which shall be executed
   296 	* @param	int		$cache_ttl	Either 0 to avoid caching or the time in seconds which the result shall be kept in cache
   297 	* @return	mixed				When casted to bool the returned value returns true on success and false on failure
   298 	*
   299 	* @access	public
   300 	*/
   301 	function sql_query($query = '', $cache_ttl = 0)
   302 	{
   303 		if ($query != '')
   304 		{
   305 			global $cache;
   306 
   307 			// EXPLAIN only in extra debug mode
   308 			if (defined('DEBUG_EXTRA'))
   309 			{
   310 				$this->sql_report('start', $query);
   311 			}
   312 
   313 			$this->last_query_text = $query;
   314 			$this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
   315 			$this->sql_add_num_queries($this->query_result);
   316 
   317 			if ($this->query_result === false)
   318 			{
   319 				if (($this->query_result = @sqlsrv_query($this->db_connect_id, $query, array(), $this->query_options)) === false)
   320 				{
   321 					$this->sql_error($query);
   322 				}
   323 				// reset options for next query
   324 				$this->query_options = array();
   325 
   326 				if (defined('DEBUG_EXTRA'))
   327 				{
   328 					$this->sql_report('stop', $query);
   329 				}
   330 
   331 				if ($cache_ttl && method_exists($cache, 'sql_save'))
   332 				{
   333 					$this->open_queries[(int) $this->query_result] = $this->query_result;
   334 					$cache->sql_save($query, $this->query_result, $cache_ttl);
   335 				}
   336 				else if (strpos($query, 'SELECT') === 0 && $this->query_result)
   337 				{
   338 					$this->open_queries[(int) $this->query_result] = $this->query_result;
   339 				}
   340 			}
   341 			else if (defined('DEBUG_EXTRA'))
   342 			{
   343 				$this->sql_report('fromcache', $query);
   344 			}
   345 		}
   346 		else
   347 		{
   348 			return false;
   349 		}
   350 		return $this->query_result;
   351 	}
   352 
   353 	/**
   354 	* Build LIMIT query
   355 	*/
   356 	function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
   357 	{
   358 		$this->query_result = false;
   359 
   360 		// total == 0 means all results - not zero results
   361 		if ($offset == 0 && $total !== 0)
   362 		{
   363 			if (strpos($query, "SELECT") === false)
   364 			{
   365 				$query = "TOP {$total} " . $query;
   366 			}
   367 			else
   368 			{
   369 				$query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP '.$total, $query);
   370 			}
   371 		}
   372 		else if ($offset > 0)
   373 		{
   374 			$query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(10000000) ', $query);
   375 			$query = 'SELECT *
   376 					FROM (SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3
   377 					FROM (SELECT 1 AS line2, sub1.* FROM (' . $query . ') AS sub1) as sub2) AS sub3';
   378 
   379 			if ($total > 0)
   380 			{
   381 				$query .= ' WHERE line3 BETWEEN ' . ($offset+1) . ' AND ' . ($offset + $total);
   382 			}
   383 			else
   384 			{
   385 				$query .= ' WHERE line3 > ' . $offset;
   386 			}
   387 		}
   388 
   389 		$result = $this->sql_query($query, $cache_ttl);
   390 
   391 		return $result;
   392 	}
   393 
   394 	/**
   395 	* Return number of affected rows
   396 	*/
   397 	function sql_affectedrows()
   398 	{
   399 		return (!empty($this->query_result)) ? @sqlsrv_rows_affected($this->query_result) : false;
   400 	}
   401 
   402 	/**
   403 	* Fetch current row
   404 	*/
   405 	function sql_fetchrow($query_id = false)
   406 	{
   407 		global $cache;
   408 
   409 		if ($query_id === false)
   410 		{
   411 			$query_id = $this->query_result;
   412 		}
   413 
   414 		if (isset($cache->sql_rowset[$query_id]))
   415 		{
   416 			return $cache->sql_fetchrow($query_id);
   417 		}
   418 
   419 		if ($query_id === false)
   420 		{
   421 			return false;
   422 		}
   423 
   424 		$row = @sqlsrv_fetch_array($query_id, SQLSRV_FETCH_ASSOC);
   425 
   426 		if ($row)
   427 		{
   428 			foreach ($row as $key => $value)
   429 			{
   430 				$row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
   431 			}
   432 
   433 			// remove helper values from LIMIT queries
   434 			if (isset($row['line2']))
   435 			{
   436 				unset($row['line2'], $row['line3']);
   437 			}
   438 		}
   439 		return $row;
   440 	}
   441 
   442 	/**
   443 	* Seek to given row number
   444 	* rownum is zero-based
   445 	*/
   446 	function sql_rowseek($rownum, &$query_id)
   447 	{
   448 		global $cache;
   449 
   450 		if (isset($cache->sql_rowset[$query_id]))
   451 		{
   452 			return $cache->sql_rowseek($rownum, $query_id);
   453 		}
   454 
   455 		$seek = new result_mssqlnative($query_id);
   456 		$row = $seek->seek($rownum);
   457 		return ($row = $seek->fetch()) ? $row : false;
   458 	}
   459 
   460 	/**
   461 	* Get last inserted id after insert statement
   462 	*/
   463 	function sql_nextid()
   464 	{
   465 		$result_id = @sqlsrv_query($this->db_connect_id, 'SELECT @@IDENTITY');
   466 
   467 		if ($result_id !== false)
   468 		{
   469 			$row = @sqlsrv_fetch_array($result_id);
   470 			$id = $row[0];
   471 			@sqlsrv_free_stmt($result_id);
   472 			return $id;
   473 		}
   474 		else
   475 		{
   476 			return false;
   477 		}
   478 	}
   479 
   480 	/**
   481 	* Free sql result
   482 	*/
   483 	function sql_freeresult($query_id = false)
   484 	{
   485 		global $cache;
   486 
   487 		if ($query_id === false)
   488 		{
   489 			$query_id = $this->query_result;
   490 		}
   491 
   492 		if (isset($cache->sql_rowset[$query_id]))
   493 		{
   494 			return $cache->sql_freeresult($query_id);
   495 		}
   496 
   497 		if (isset($this->open_queries[$query_id]))
   498 		{
   499 			unset($this->open_queries[$query_id]);
   500 			return @sqlsrv_free_stmt($query_id);
   501 		}
   502 		return false;
   503 	}
   504 
   505 	/**
   506 	* Escape string used in sql query
   507 	*/
   508 	function sql_escape($msg)
   509 	{
   510 		return str_replace(array("'", "\0"), array("''", ''), $msg);
   511 	}
   512 
   513 	/**
   514 	* Build LIKE expression
   515 	* @access private
   516 	*/
   517 	function _sql_like_expression($expression)
   518 	{
   519 		return $expression . " ESCAPE '\\'";
   520 	}
   521 
   522 	/**
   523 	* return sql error array
   524 	* @access private
   525 	*/
   526 	function _sql_error()
   527 	{
   528 		$errors = @sqlsrv_errors(SQLSRV_ERR_ERRORS);
   529 		$error_message = '';
   530 		$code = 0;
   531 
   532 		if ($errors != null)
   533 		{
   534 			foreach ($errors as $error)
   535 			{
   536 				$error_message .= "SQLSTATE: ".$error[ 'SQLSTATE']."\n";
   537 				$error_message .= "code: ".$error[ 'code']."\n";
   538 				$code = $error['code'];
   539 				$error_message .= "message: ".$error[ 'message']."\n";
   540 			}
   541 			$this->last_error_result = $error_message;
   542 			$error = $this->last_error_result;
   543 		}
   544 		else
   545 		{
   546 			$error = (isset($this->last_error_result) && $this->last_error_result) ? $this->last_error_result : array();
   547 		}
   548 
   549 		return array(
   550 			'message'	=> $error,
   551 			'code'		=> $code,
   552 		);
   553 	}
   554 
   555 	/**
   556 	* Build db-specific query data
   557 	* @access private
   558 	*/
   559 	function _sql_custom_build($stage, $data)
   560 	{
   561 		return $data;
   562 	}
   563 
   564 	/**
   565 	* Close sql connection
   566 	* @access private
   567 	*/
   568 	function _sql_close()
   569 	{
   570 		return @sqlsrv_close($this->db_connect_id);
   571 	}
   572 
   573 	/**
   574 	* Build db-specific report
   575 	* @access private
   576 	*/
   577 	function _sql_report($mode, $query = '')
   578 	{
   579 		switch ($mode)
   580 		{
   581 			case 'start':
   582 				$html_table = false;
   583 				@sqlsrv_query($this->db_connect_id, 'SET SHOWPLAN_TEXT ON;');
   584 				if ($result = @sqlsrv_query($this->db_connect_id, $query))
   585 				{
   586 					@sqlsrv_next_result($result);
   587 					while ($row = @sqlsrv_fetch_array($result))
   588 					{
   589 						$html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
   590 					}
   591 				}
   592 				@sqlsrv_query($this->db_connect_id, 'SET SHOWPLAN_TEXT OFF;');
   593 				@sqlsrv_free_stmt($result);
   594 
   595 				if ($html_table)
   596 				{
   597 					$this->html_hold .= '</table>';
   598 				}
   599 			break;
   600 
   601 			case 'fromcache':
   602 				$endtime = explode(' ', microtime());
   603 				$endtime = $endtime[0] + $endtime[1];
   604 
   605 				$result = @sqlsrv_query($this->db_connect_id, $query);
   606 				while ($void = @sqlsrv_fetch_array($result))
   607 				{
   608 					// Take the time spent on parsing rows into account
   609 				}
   610 				@sqlsrv_free_stmt($result);
   611 
   612 				$splittime = explode(' ', microtime());
   613 				$splittime = $splittime[0] + $splittime[1];
   614 
   615 				$this->sql_report('record_fromcache', $query, $endtime, $splittime);
   616 
   617 			break;
   618 		}
   619 	}
   620 
   621 	/**
   622 	* Utility method used to retrieve number of rows
   623 	* Emulates mysql_num_rows
   624 	* Used in acp_database.php -> write_data_mssqlnative()
   625 	* Requires a static or keyset cursor to be definde via
   626 	* mssqlnative_set_query_options()
   627 	*/
   628 	function mssqlnative_num_rows($res)
   629 	{
   630 		if ($res !== false)
   631 		{
   632 			return sqlsrv_num_rows($res);
   633 		}
   634 		else
   635 		{
   636 			return false;
   637 		}
   638 	}
   639 
   640 	/**
   641 	* Allows setting mssqlnative specific query options passed to sqlsrv_query as 4th parameter.
   642 	*/
   643 	function mssqlnative_set_query_options($options)
   644 	{
   645 		$this->query_options = $options;
   646 	}
   647 }
   648 
   649 ?>