1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/includes/db/mssqlnative.php Wed Mar 07 16:41:10 2012 +0400
1.3 @@ -0,0 +1,649 @@
1.4 +<?php
1.5 +/**
1.6 +*
1.7 +* @package dbal
1.8 +* @version $Id$
1.9 +* @copyright (c) 2010 phpBB Group
1.10 +* @license http://opensource.org/licenses/gpl-license.php GNU Public License
1.11 +*
1.12 +* This is the MS SQL Server Native database abstraction layer.
1.13 +* PHP mssql native driver required.
1.14 +* @author Chris Pucci
1.15 +*
1.16 +*/
1.17 +
1.18 +/**
1.19 +* @ignore
1.20 +*/
1.21 +if (!defined('IN_PHPBB'))
1.22 +{
1.23 + exit;
1.24 +}
1.25 +
1.26 +include_once($phpbb_root_path . 'includes/db/dbal.' . $phpEx);
1.27 +
1.28 +/**
1.29 + * 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
1.30 + * and maintain our own cursor index into that array.
1.31 + */
1.32 +class result_mssqlnative
1.33 +{
1.34 + public function result_mssqlnative($queryresult = false)
1.35 + {
1.36 + $this->m_cursor = 0;
1.37 + $this->m_rows = array();
1.38 + $this->m_num_fields = sqlsrv_num_fields($queryresult);
1.39 + $this->m_field_meta = sqlsrv_field_metadata($queryresult);
1.40 +
1.41 + while ($row = sqlsrv_fetch_array($queryresult, SQLSRV_FETCH_ASSOC))
1.42 + {
1.43 + if ($row !== null)
1.44 + {
1.45 + foreach($row as $k => $v)
1.46 + {
1.47 + if (is_object($v) && method_exists($v, 'format'))
1.48 + {
1.49 + $row[$k] = $v->format("Y-m-d\TH:i:s\Z");
1.50 + }
1.51 + }
1.52 + $this->m_rows[] = $row;//read results into memory, cursors are not supported
1.53 + }
1.54 + }
1.55 +
1.56 + $this->m_row_count = sizeof($this->m_rows);
1.57 + }
1.58 +
1.59 + private function array_to_obj($array, &$obj)
1.60 + {
1.61 + foreach ($array as $key => $value)
1.62 + {
1.63 + if (is_array($value))
1.64 + {
1.65 + $obj->$key = new stdClass();
1.66 + array_to_obj($value, $obj->$key);
1.67 + }
1.68 + else
1.69 + {
1.70 + $obj->$key = $value;
1.71 + }
1.72 + }
1.73 + return $obj;
1.74 + }
1.75 +
1.76 + public function fetch($mode = SQLSRV_FETCH_BOTH, $object_class = 'stdClass')
1.77 + {
1.78 + if ($this->m_cursor >= $this->m_row_count || $this->m_row_count == 0)
1.79 + {
1.80 + return false;
1.81 + }
1.82 +
1.83 + $ret = false;
1.84 + $arr_num = array();
1.85 +
1.86 + if ($mode == SQLSRV_FETCH_NUMERIC || $mode == SQLSRV_FETCH_BOTH)
1.87 + {
1.88 + foreach($this->m_rows[$this->m_cursor] as $key => $value)
1.89 + {
1.90 + $arr_num[] = $value;
1.91 + }
1.92 + }
1.93 +
1.94 + switch ($mode)
1.95 + {
1.96 + case SQLSRV_FETCH_ASSOC:
1.97 + $ret = $this->m_rows[$this->m_cursor];
1.98 + break;
1.99 + case SQLSRV_FETCH_NUMERIC:
1.100 + $ret = $arr_num;
1.101 + break;
1.102 + case 'OBJECT':
1.103 + $ret = $this->array_to_obj($this->m_rows[$this->m_cursor], $o = new $object_class);
1.104 + break;
1.105 + case SQLSRV_FETCH_BOTH:
1.106 + default:
1.107 + $ret = $this->m_rows[$this->m_cursor] + $arr_num;
1.108 + break;
1.109 + }
1.110 + $this->m_cursor++;
1.111 + return $ret;
1.112 + }
1.113 +
1.114 + public function get($pos, $fld)
1.115 + {
1.116 + return $this->m_rows[$pos][$fld];
1.117 + }
1.118 +
1.119 + public function num_rows()
1.120 + {
1.121 + return $this->m_row_count;
1.122 + }
1.123 +
1.124 + public function seek($iRow)
1.125 + {
1.126 + $this->m_cursor = min($iRow, $this->m_row_count);
1.127 + }
1.128 +
1.129 + public function num_fields()
1.130 + {
1.131 + return $this->m_num_fields;
1.132 + }
1.133 +
1.134 + public function field_name($nr)
1.135 + {
1.136 + $arr_keys = array_keys($this->m_rows[0]);
1.137 + return $arr_keys[$nr];
1.138 + }
1.139 +
1.140 + public function field_type($nr)
1.141 + {
1.142 + $i = 0;
1.143 + $int_type = -1;
1.144 + $str_type = '';
1.145 +
1.146 + foreach ($this->m_field_meta as $meta)
1.147 + {
1.148 + if ($nr == $i)
1.149 + {
1.150 + $int_type = $meta['Type'];
1.151 + break;
1.152 + }
1.153 + $i++;
1.154 + }
1.155 +
1.156 + //http://msdn.microsoft.com/en-us/library/cc296183.aspx contains type table
1.157 + switch ($int_type)
1.158 + {
1.159 + case SQLSRV_SQLTYPE_BIGINT: $str_type = 'bigint'; break;
1.160 + case SQLSRV_SQLTYPE_BINARY: $str_type = 'binary'; break;
1.161 + case SQLSRV_SQLTYPE_BIT: $str_type = 'bit'; break;
1.162 + case SQLSRV_SQLTYPE_CHAR: $str_type = 'char'; break;
1.163 + case SQLSRV_SQLTYPE_DATETIME: $str_type = 'datetime'; break;
1.164 + case SQLSRV_SQLTYPE_DECIMAL/*($precision, $scale)*/: $str_type = 'decimal'; break;
1.165 + case SQLSRV_SQLTYPE_FLOAT: $str_type = 'float'; break;
1.166 + case SQLSRV_SQLTYPE_IMAGE: $str_type = 'image'; break;
1.167 + case SQLSRV_SQLTYPE_INT: $str_type = 'int'; break;
1.168 + case SQLSRV_SQLTYPE_MONEY: $str_type = 'money'; break;
1.169 + case SQLSRV_SQLTYPE_NCHAR/*($charCount)*/: $str_type = 'nchar'; break;
1.170 + case SQLSRV_SQLTYPE_NUMERIC/*($precision, $scale)*/: $str_type = 'numeric'; break;
1.171 + case SQLSRV_SQLTYPE_NVARCHAR/*($charCount)*/: $str_type = 'nvarchar'; break;
1.172 + case SQLSRV_SQLTYPE_NTEXT: $str_type = 'ntext'; break;
1.173 + case SQLSRV_SQLTYPE_REAL: $str_type = 'real'; break;
1.174 + case SQLSRV_SQLTYPE_SMALLDATETIME: $str_type = 'smalldatetime'; break;
1.175 + case SQLSRV_SQLTYPE_SMALLINT: $str_type = 'smallint'; break;
1.176 + case SQLSRV_SQLTYPE_SMALLMONEY: $str_type = 'smallmoney'; break;
1.177 + case SQLSRV_SQLTYPE_TEXT: $str_type = 'text'; break;
1.178 + case SQLSRV_SQLTYPE_TIMESTAMP: $str_type = 'timestamp'; break;
1.179 + case SQLSRV_SQLTYPE_TINYINT: $str_type = 'tinyint'; break;
1.180 + case SQLSRV_SQLTYPE_UNIQUEIDENTIFIER: $str_type = 'uniqueidentifier'; break;
1.181 + case SQLSRV_SQLTYPE_UDT: $str_type = 'UDT'; break;
1.182 + case SQLSRV_SQLTYPE_VARBINARY/*($byteCount)*/: $str_type = 'varbinary'; break;
1.183 + case SQLSRV_SQLTYPE_VARCHAR/*($charCount)*/: $str_type = 'varchar'; break;
1.184 + case SQLSRV_SQLTYPE_XML: $str_type = 'xml'; break;
1.185 + default: $str_type = $int_type;
1.186 + }
1.187 + return $str_type;
1.188 + }
1.189 +
1.190 + public function free()
1.191 + {
1.192 + unset($this->m_rows);
1.193 + return;
1.194 + }
1.195 +}
1.196 +
1.197 +/**
1.198 +* @package dbal
1.199 +*/
1.200 +class dbal_mssqlnative extends dbal
1.201 +{
1.202 + var $m_insert_id = NULL;
1.203 + var $last_query_text = '';
1.204 + var $query_options = array();
1.205 +
1.206 + /**
1.207 + * Connect to server
1.208 + */
1.209 + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
1.210 + {
1.211 + # Test for driver support, to avoid suppressed fatal error
1.212 + if (!function_exists('sqlsrv_connect'))
1.213 + {
1.214 + 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);
1.215 + }
1.216 +
1.217 + //set up connection variables
1.218 + $this->persistency = $persistency;
1.219 + $this->user = $sqluser;
1.220 + $this->dbname = $database;
1.221 + $port_delimiter = (defined('PHP_OS') && substr(PHP_OS, 0, 3) === 'WIN') ? ',' : ':';
1.222 + $this->server = $sqlserver . (($port) ? $port_delimiter . $port : '');
1.223 +
1.224 + //connect to database
1.225 + error_reporting(E_ALL);
1.226 + $this->db_connect_id = sqlsrv_connect($this->server, array(
1.227 + 'Database' => $this->dbname,
1.228 + 'UID' => $this->user,
1.229 + 'PWD' => $sqlpassword
1.230 + ));
1.231 +
1.232 + return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
1.233 + }
1.234 +
1.235 + /**
1.236 + * Version information about used database
1.237 + * @param bool $raw if true, only return the fetched sql_server_version
1.238 + * @param bool $use_cache If true, it is safe to retrieve the value from the cache
1.239 + * @return string sql server version
1.240 + */
1.241 + function sql_server_info($raw = false, $use_cache = true)
1.242 + {
1.243 + global $cache;
1.244 +
1.245 + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mssql_version')) === false)
1.246 + {
1.247 + $arr_server_info = sqlsrv_server_info($this->db_connect_id);
1.248 + $this->sql_server_version = $arr_server_info['SQLServerVersion'];
1.249 +
1.250 + if (!empty($cache) && $use_cache)
1.251 + {
1.252 + $cache->put('mssql_version', $this->sql_server_version);
1.253 + }
1.254 + }
1.255 +
1.256 + if ($raw)
1.257 + {
1.258 + return $this->sql_server_version;
1.259 + }
1.260 +
1.261 + return ($this->sql_server_version) ? 'MSSQL<br />' . $this->sql_server_version : 'MSSQL';
1.262 + }
1.263 +
1.264 + /**
1.265 + * {@inheritDoc}
1.266 + */
1.267 + function sql_buffer_nested_transactions()
1.268 + {
1.269 + return true;
1.270 + }
1.271 +
1.272 + /**
1.273 + * SQL Transaction
1.274 + * @access private
1.275 + */
1.276 + function _sql_transaction($status = 'begin')
1.277 + {
1.278 + switch ($status)
1.279 + {
1.280 + case 'begin':
1.281 + return sqlsrv_begin_transaction($this->db_connect_id);
1.282 + break;
1.283 +
1.284 + case 'commit':
1.285 + return sqlsrv_commit($this->db_connect_id);
1.286 + break;
1.287 +
1.288 + case 'rollback':
1.289 + return sqlsrv_rollback($this->db_connect_id);
1.290 + break;
1.291 + }
1.292 + return true;
1.293 + }
1.294 +
1.295 + /**
1.296 + * Base query method
1.297 + *
1.298 + * @param string $query Contains the SQL query which shall be executed
1.299 + * @param int $cache_ttl Either 0 to avoid caching or the time in seconds which the result shall be kept in cache
1.300 + * @return mixed When casted to bool the returned value returns true on success and false on failure
1.301 + *
1.302 + * @access public
1.303 + */
1.304 + function sql_query($query = '', $cache_ttl = 0)
1.305 + {
1.306 + if ($query != '')
1.307 + {
1.308 + global $cache;
1.309 +
1.310 + // EXPLAIN only in extra debug mode
1.311 + if (defined('DEBUG_EXTRA'))
1.312 + {
1.313 + $this->sql_report('start', $query);
1.314 + }
1.315 +
1.316 + $this->last_query_text = $query;
1.317 + $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
1.318 + $this->sql_add_num_queries($this->query_result);
1.319 +
1.320 + if ($this->query_result === false)
1.321 + {
1.322 + if (($this->query_result = @sqlsrv_query($this->db_connect_id, $query, array(), $this->query_options)) === false)
1.323 + {
1.324 + $this->sql_error($query);
1.325 + }
1.326 + // reset options for next query
1.327 + $this->query_options = array();
1.328 +
1.329 + if (defined('DEBUG_EXTRA'))
1.330 + {
1.331 + $this->sql_report('stop', $query);
1.332 + }
1.333 +
1.334 + if ($cache_ttl && method_exists($cache, 'sql_save'))
1.335 + {
1.336 + $this->open_queries[(int) $this->query_result] = $this->query_result;
1.337 + $cache->sql_save($query, $this->query_result, $cache_ttl);
1.338 + }
1.339 + else if (strpos($query, 'SELECT') === 0 && $this->query_result)
1.340 + {
1.341 + $this->open_queries[(int) $this->query_result] = $this->query_result;
1.342 + }
1.343 + }
1.344 + else if (defined('DEBUG_EXTRA'))
1.345 + {
1.346 + $this->sql_report('fromcache', $query);
1.347 + }
1.348 + }
1.349 + else
1.350 + {
1.351 + return false;
1.352 + }
1.353 + return $this->query_result;
1.354 + }
1.355 +
1.356 + /**
1.357 + * Build LIMIT query
1.358 + */
1.359 + function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
1.360 + {
1.361 + $this->query_result = false;
1.362 +
1.363 + // total == 0 means all results - not zero results
1.364 + if ($offset == 0 && $total !== 0)
1.365 + {
1.366 + if (strpos($query, "SELECT") === false)
1.367 + {
1.368 + $query = "TOP {$total} " . $query;
1.369 + }
1.370 + else
1.371 + {
1.372 + $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP '.$total, $query);
1.373 + }
1.374 + }
1.375 + else if ($offset > 0)
1.376 + {
1.377 + $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(10000000) ', $query);
1.378 + $query = 'SELECT *
1.379 + FROM (SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3
1.380 + FROM (SELECT 1 AS line2, sub1.* FROM (' . $query . ') AS sub1) as sub2) AS sub3';
1.381 +
1.382 + if ($total > 0)
1.383 + {
1.384 + $query .= ' WHERE line3 BETWEEN ' . ($offset+1) . ' AND ' . ($offset + $total);
1.385 + }
1.386 + else
1.387 + {
1.388 + $query .= ' WHERE line3 > ' . $offset;
1.389 + }
1.390 + }
1.391 +
1.392 + $result = $this->sql_query($query, $cache_ttl);
1.393 +
1.394 + return $result;
1.395 + }
1.396 +
1.397 + /**
1.398 + * Return number of affected rows
1.399 + */
1.400 + function sql_affectedrows()
1.401 + {
1.402 + return (!empty($this->query_result)) ? @sqlsrv_rows_affected($this->query_result) : false;
1.403 + }
1.404 +
1.405 + /**
1.406 + * Fetch current row
1.407 + */
1.408 + function sql_fetchrow($query_id = false)
1.409 + {
1.410 + global $cache;
1.411 +
1.412 + if ($query_id === false)
1.413 + {
1.414 + $query_id = $this->query_result;
1.415 + }
1.416 +
1.417 + if (isset($cache->sql_rowset[$query_id]))
1.418 + {
1.419 + return $cache->sql_fetchrow($query_id);
1.420 + }
1.421 +
1.422 + if ($query_id === false)
1.423 + {
1.424 + return false;
1.425 + }
1.426 +
1.427 + $row = @sqlsrv_fetch_array($query_id, SQLSRV_FETCH_ASSOC);
1.428 +
1.429 + if ($row)
1.430 + {
1.431 + foreach ($row as $key => $value)
1.432 + {
1.433 + $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
1.434 + }
1.435 +
1.436 + // remove helper values from LIMIT queries
1.437 + if (isset($row['line2']))
1.438 + {
1.439 + unset($row['line2'], $row['line3']);
1.440 + }
1.441 + }
1.442 + return $row;
1.443 + }
1.444 +
1.445 + /**
1.446 + * Seek to given row number
1.447 + * rownum is zero-based
1.448 + */
1.449 + function sql_rowseek($rownum, &$query_id)
1.450 + {
1.451 + global $cache;
1.452 +
1.453 + if (isset($cache->sql_rowset[$query_id]))
1.454 + {
1.455 + return $cache->sql_rowseek($rownum, $query_id);
1.456 + }
1.457 +
1.458 + $seek = new result_mssqlnative($query_id);
1.459 + $row = $seek->seek($rownum);
1.460 + return ($row = $seek->fetch()) ? $row : false;
1.461 + }
1.462 +
1.463 + /**
1.464 + * Get last inserted id after insert statement
1.465 + */
1.466 + function sql_nextid()
1.467 + {
1.468 + $result_id = @sqlsrv_query($this->db_connect_id, 'SELECT @@IDENTITY');
1.469 +
1.470 + if ($result_id !== false)
1.471 + {
1.472 + $row = @sqlsrv_fetch_array($result_id);
1.473 + $id = $row[0];
1.474 + @sqlsrv_free_stmt($result_id);
1.475 + return $id;
1.476 + }
1.477 + else
1.478 + {
1.479 + return false;
1.480 + }
1.481 + }
1.482 +
1.483 + /**
1.484 + * Free sql result
1.485 + */
1.486 + function sql_freeresult($query_id = false)
1.487 + {
1.488 + global $cache;
1.489 +
1.490 + if ($query_id === false)
1.491 + {
1.492 + $query_id = $this->query_result;
1.493 + }
1.494 +
1.495 + if (isset($cache->sql_rowset[$query_id]))
1.496 + {
1.497 + return $cache->sql_freeresult($query_id);
1.498 + }
1.499 +
1.500 + if (isset($this->open_queries[$query_id]))
1.501 + {
1.502 + unset($this->open_queries[$query_id]);
1.503 + return @sqlsrv_free_stmt($query_id);
1.504 + }
1.505 + return false;
1.506 + }
1.507 +
1.508 + /**
1.509 + * Escape string used in sql query
1.510 + */
1.511 + function sql_escape($msg)
1.512 + {
1.513 + return str_replace(array("'", "\0"), array("''", ''), $msg);
1.514 + }
1.515 +
1.516 + /**
1.517 + * Build LIKE expression
1.518 + * @access private
1.519 + */
1.520 + function _sql_like_expression($expression)
1.521 + {
1.522 + return $expression . " ESCAPE '\\'";
1.523 + }
1.524 +
1.525 + /**
1.526 + * return sql error array
1.527 + * @access private
1.528 + */
1.529 + function _sql_error()
1.530 + {
1.531 + $errors = @sqlsrv_errors(SQLSRV_ERR_ERRORS);
1.532 + $error_message = '';
1.533 + $code = 0;
1.534 +
1.535 + if ($errors != null)
1.536 + {
1.537 + foreach ($errors as $error)
1.538 + {
1.539 + $error_message .= "SQLSTATE: ".$error[ 'SQLSTATE']."\n";
1.540 + $error_message .= "code: ".$error[ 'code']."\n";
1.541 + $code = $error['code'];
1.542 + $error_message .= "message: ".$error[ 'message']."\n";
1.543 + }
1.544 + $this->last_error_result = $error_message;
1.545 + $error = $this->last_error_result;
1.546 + }
1.547 + else
1.548 + {
1.549 + $error = (isset($this->last_error_result) && $this->last_error_result) ? $this->last_error_result : array();
1.550 + }
1.551 +
1.552 + return array(
1.553 + 'message' => $error,
1.554 + 'code' => $code,
1.555 + );
1.556 + }
1.557 +
1.558 + /**
1.559 + * Build db-specific query data
1.560 + * @access private
1.561 + */
1.562 + function _sql_custom_build($stage, $data)
1.563 + {
1.564 + return $data;
1.565 + }
1.566 +
1.567 + /**
1.568 + * Close sql connection
1.569 + * @access private
1.570 + */
1.571 + function _sql_close()
1.572 + {
1.573 + return @sqlsrv_close($this->db_connect_id);
1.574 + }
1.575 +
1.576 + /**
1.577 + * Build db-specific report
1.578 + * @access private
1.579 + */
1.580 + function _sql_report($mode, $query = '')
1.581 + {
1.582 + switch ($mode)
1.583 + {
1.584 + case 'start':
1.585 + $html_table = false;
1.586 + @sqlsrv_query($this->db_connect_id, 'SET SHOWPLAN_TEXT ON;');
1.587 + if ($result = @sqlsrv_query($this->db_connect_id, $query))
1.588 + {
1.589 + @sqlsrv_next_result($result);
1.590 + while ($row = @sqlsrv_fetch_array($result))
1.591 + {
1.592 + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
1.593 + }
1.594 + }
1.595 + @sqlsrv_query($this->db_connect_id, 'SET SHOWPLAN_TEXT OFF;');
1.596 + @sqlsrv_free_stmt($result);
1.597 +
1.598 + if ($html_table)
1.599 + {
1.600 + $this->html_hold .= '</table>';
1.601 + }
1.602 + break;
1.603 +
1.604 + case 'fromcache':
1.605 + $endtime = explode(' ', microtime());
1.606 + $endtime = $endtime[0] + $endtime[1];
1.607 +
1.608 + $result = @sqlsrv_query($this->db_connect_id, $query);
1.609 + while ($void = @sqlsrv_fetch_array($result))
1.610 + {
1.611 + // Take the time spent on parsing rows into account
1.612 + }
1.613 + @sqlsrv_free_stmt($result);
1.614 +
1.615 + $splittime = explode(' ', microtime());
1.616 + $splittime = $splittime[0] + $splittime[1];
1.617 +
1.618 + $this->sql_report('record_fromcache', $query, $endtime, $splittime);
1.619 +
1.620 + break;
1.621 + }
1.622 + }
1.623 +
1.624 + /**
1.625 + * Utility method used to retrieve number of rows
1.626 + * Emulates mysql_num_rows
1.627 + * Used in acp_database.php -> write_data_mssqlnative()
1.628 + * Requires a static or keyset cursor to be definde via
1.629 + * mssqlnative_set_query_options()
1.630 + */
1.631 + function mssqlnative_num_rows($res)
1.632 + {
1.633 + if ($res !== false)
1.634 + {
1.635 + return sqlsrv_num_rows($res);
1.636 + }
1.637 + else
1.638 + {
1.639 + return false;
1.640 + }
1.641 + }
1.642 +
1.643 + /**
1.644 + * Allows setting mssqlnative specific query options passed to sqlsrv_query as 4th parameter.
1.645 + */
1.646 + function mssqlnative_set_query_options($options)
1.647 + {
1.648 + $this->query_options = $options;
1.649 + }
1.650 +}
1.651 +
1.652 +?>