6 * @copyright (c) 2010 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 * This is the MS SQL Server Native database abstraction layer.
10 * PHP mssql native driver required.
18 if (!defined('IN_PHPBB'))
23 include_once($phpbb_root_path . 'includes/db/dbal.' . $phpEx);
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.
29 class result_mssqlnative
31 public function result_mssqlnative($queryresult = false)
34 $this->m_rows = array();
35 $this->m_num_fields = sqlsrv_num_fields($queryresult);
36 $this->m_field_meta = sqlsrv_field_metadata($queryresult);
38 while ($row = sqlsrv_fetch_array($queryresult, SQLSRV_FETCH_ASSOC))
42 foreach($row as $k => $v)
44 if (is_object($v) && method_exists($v, 'format'))
46 $row[$k] = $v->format("Y-m-d\TH:i:s\Z");
49 $this->m_rows[] = $row;//read results into memory, cursors are not supported
53 $this->m_row_count = sizeof($this->m_rows);
56 private function array_to_obj($array, &$obj)
58 foreach ($array as $key => $value)
62 $obj->$key = new stdClass();
63 array_to_obj($value, $obj->$key);
73 public function fetch($mode = SQLSRV_FETCH_BOTH, $object_class = 'stdClass')
75 if ($this->m_cursor >= $this->m_row_count || $this->m_row_count == 0)
83 if ($mode == SQLSRV_FETCH_NUMERIC || $mode == SQLSRV_FETCH_BOTH)
85 foreach($this->m_rows[$this->m_cursor] as $key => $value)
93 case SQLSRV_FETCH_ASSOC:
94 $ret = $this->m_rows[$this->m_cursor];
96 case SQLSRV_FETCH_NUMERIC:
100 $ret = $this->array_to_obj($this->m_rows[$this->m_cursor], $o = new $object_class);
102 case SQLSRV_FETCH_BOTH:
104 $ret = $this->m_rows[$this->m_cursor] + $arr_num;
111 public function get($pos, $fld)
113 return $this->m_rows[$pos][$fld];
116 public function num_rows()
118 return $this->m_row_count;
121 public function seek($iRow)
123 $this->m_cursor = min($iRow, $this->m_row_count);
126 public function num_fields()
128 return $this->m_num_fields;
131 public function field_name($nr)
133 $arr_keys = array_keys($this->m_rows[0]);
134 return $arr_keys[$nr];
137 public function field_type($nr)
143 foreach ($this->m_field_meta as $meta)
147 $int_type = $meta['Type'];
153 //http://msdn.microsoft.com/en-us/library/cc296183.aspx contains type table
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;
187 public function free()
189 unset($this->m_rows);
197 class dbal_mssqlnative extends dbal
199 var $m_insert_id = NULL;
200 var $last_query_text = '';
201 var $query_options = array();
206 function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
208 # Test for driver support, to avoid suppressed fatal error
209 if (!function_exists('sqlsrv_connect'))
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);
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 : '');
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
229 return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
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
238 function sql_server_info($raw = false, $use_cache = true)
242 if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mssql_version')) === false)
244 $arr_server_info = sqlsrv_server_info($this->db_connect_id);
245 $this->sql_server_version = $arr_server_info['SQLServerVersion'];
247 if (!empty($cache) && $use_cache)
249 $cache->put('mssql_version', $this->sql_server_version);
255 return $this->sql_server_version;
258 return ($this->sql_server_version) ? 'MSSQL<br />' . $this->sql_server_version : 'MSSQL';
264 function sql_buffer_nested_transactions()
273 function _sql_transaction($status = 'begin')
278 return sqlsrv_begin_transaction($this->db_connect_id);
282 return sqlsrv_commit($this->db_connect_id);
286 return sqlsrv_rollback($this->db_connect_id);
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
301 function sql_query($query = '', $cache_ttl = 0)
307 // EXPLAIN only in extra debug mode
308 if (defined('DEBUG_EXTRA'))
310 $this->sql_report('start', $query);
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);
317 if ($this->query_result === false)
319 if (($this->query_result = @sqlsrv_query($this->db_connect_id, $query, array(), $this->query_options)) === false)
321 $this->sql_error($query);
323 // reset options for next query
324 $this->query_options = array();
326 if (defined('DEBUG_EXTRA'))
328 $this->sql_report('stop', $query);
331 if ($cache_ttl && method_exists($cache, 'sql_save'))
333 $this->open_queries[(int) $this->query_result] = $this->query_result;
334 $cache->sql_save($query, $this->query_result, $cache_ttl);
336 else if (strpos($query, 'SELECT') === 0 && $this->query_result)
338 $this->open_queries[(int) $this->query_result] = $this->query_result;
341 else if (defined('DEBUG_EXTRA'))
343 $this->sql_report('fromcache', $query);
350 return $this->query_result;
356 function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
358 $this->query_result = false;
360 // total == 0 means all results - not zero results
361 if ($offset == 0 && $total !== 0)
363 if (strpos($query, "SELECT") === false)
365 $query = "TOP {$total} " . $query;
369 $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP '.$total, $query);
372 else if ($offset > 0)
374 $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(10000000) ', $query);
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';
381 $query .= ' WHERE line3 BETWEEN ' . ($offset+1) . ' AND ' . ($offset + $total);
385 $query .= ' WHERE line3 > ' . $offset;
389 $result = $this->sql_query($query, $cache_ttl);
395 * Return number of affected rows
397 function sql_affectedrows()
399 return (!empty($this->query_result)) ? @sqlsrv_rows_affected($this->query_result) : false;
405 function sql_fetchrow($query_id = false)
409 if ($query_id === false)
411 $query_id = $this->query_result;
414 if (isset($cache->sql_rowset[$query_id]))
416 return $cache->sql_fetchrow($query_id);
419 if ($query_id === false)
424 $row = @sqlsrv_fetch_array($query_id, SQLSRV_FETCH_ASSOC);
428 foreach ($row as $key => $value)
430 $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
433 // remove helper values from LIMIT queries
434 if (isset($row['line2']))
436 unset($row['line2'], $row['line3']);
443 * Seek to given row number
444 * rownum is zero-based
446 function sql_rowseek($rownum, &$query_id)
450 if (isset($cache->sql_rowset[$query_id]))
452 return $cache->sql_rowseek($rownum, $query_id);
455 $seek = new result_mssqlnative($query_id);
456 $row = $seek->seek($rownum);
457 return ($row = $seek->fetch()) ? $row : false;
461 * Get last inserted id after insert statement
463 function sql_nextid()
465 $result_id = @sqlsrv_query($this->db_connect_id, 'SELECT @@IDENTITY');
467 if ($result_id !== false)
469 $row = @sqlsrv_fetch_array($result_id);
471 @sqlsrv_free_stmt($result_id);
483 function sql_freeresult($query_id = false)
487 if ($query_id === false)
489 $query_id = $this->query_result;
492 if (isset($cache->sql_rowset[$query_id]))
494 return $cache->sql_freeresult($query_id);
497 if (isset($this->open_queries[$query_id]))
499 unset($this->open_queries[$query_id]);
500 return @sqlsrv_free_stmt($query_id);
506 * Escape string used in sql query
508 function sql_escape($msg)
510 return str_replace(array("'", "\0"), array("''", ''), $msg);
514 * Build LIKE expression
517 function _sql_like_expression($expression)
519 return $expression . " ESCAPE '\\'";
523 * return sql error array
526 function _sql_error()
528 $errors = @sqlsrv_errors(SQLSRV_ERR_ERRORS);
534 foreach ($errors as $error)
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";
541 $this->last_error_result = $error_message;
542 $error = $this->last_error_result;
546 $error = (isset($this->last_error_result) && $this->last_error_result) ? $this->last_error_result : array();
556 * Build db-specific query data
559 function _sql_custom_build($stage, $data)
565 * Close sql connection
568 function _sql_close()
570 return @sqlsrv_close($this->db_connect_id);
574 * Build db-specific report
577 function _sql_report($mode, $query = '')
583 @sqlsrv_query($this->db_connect_id, 'SET SHOWPLAN_TEXT ON;');
584 if ($result = @sqlsrv_query($this->db_connect_id, $query))
586 @sqlsrv_next_result($result);
587 while ($row = @sqlsrv_fetch_array($result))
589 $html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
592 @sqlsrv_query($this->db_connect_id, 'SET SHOWPLAN_TEXT OFF;');
593 @sqlsrv_free_stmt($result);
597 $this->html_hold .= '</table>';
602 $endtime = explode(' ', microtime());
603 $endtime = $endtime[0] + $endtime[1];
605 $result = @sqlsrv_query($this->db_connect_id, $query);
606 while ($void = @sqlsrv_fetch_array($result))
608 // Take the time spent on parsing rows into account
610 @sqlsrv_free_stmt($result);
612 $splittime = explode(' ', microtime());
613 $splittime = $splittime[0] + $splittime[1];
615 $this->sql_report('record_fromcache', $query, $endtime, $splittime);
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()
628 function mssqlnative_num_rows($res)
632 return sqlsrv_num_rows($res);
641 * Allows setting mssqlnative specific query options passed to sqlsrv_query as 4th parameter.
643 function mssqlnative_set_query_options($options)
645 $this->query_options = $options;