3 * This is the MS SQL Server Native database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author Joel Penner <a-joelpe at microsoft dot com>
23 * @author Chris Pucci <a-cpucci at microsoft dot com>
24 * @author Ryan Biesemeyer <v-ryanbi at microsoft dot com>
25 * @author Ryan Schmidt <skizzerz at gmail dot com>
31 class DatabaseMssql
extends DatabaseBase
{
32 protected $mInsertId = null;
33 protected $mLastResult = null;
34 protected $mAffectedRows = null;
35 protected $mSubqueryId = 0;
36 protected $mScrollableCursor = true;
37 protected $mPrepareStatements = true;
38 protected $mBinaryColumnCache = null;
39 protected $mBitColumnCache = null;
40 protected $mIgnoreDupKeyErrors = false;
44 public function cascadingDeletes() {
48 public function cleanupTriggers() {
52 public function strictIPs() {
56 public function realTimestamps() {
60 public function implicitGroupby() {
64 public function implicitOrderby() {
68 public function functionalIndexes() {
72 public function unionSupportsOrderAndLimit() {
77 * Usually aborts on failure
78 * @param string $server
80 * @param string $password
81 * @param string $dbName
82 * @throws DBConnectionError
83 * @return bool|DatabaseBase|null
85 public function open( $server, $user, $password, $dbName ) {
86 # Test for driver support, to avoid suppressed fatal error
87 if ( !function_exists( 'sqlsrv_connect' ) ) {
88 throw new DBConnectionError(
90 "Microsoft SQL Server Native (sqlsrv) functions missing.
91 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
95 global $wgDBport, $wgDBWindowsAuthentication;
97 # e.g. the class is being loaded
98 if ( !strlen( $user ) ) {
103 $this->mServer
= $server;
104 $this->mPort
= $wgDBport;
105 $this->mUser
= $user;
106 $this->mPassword
= $password;
107 $this->mDBname
= $dbName;
109 $connectionInfo = array();
112 $connectionInfo['Database'] = $dbName;
115 // Decide which auth scenerio to use
116 // if we are using Windows auth, don't add credentials to $connectionInfo
117 if ( !$wgDBWindowsAuthentication ) {
118 $connectionInfo['UID'] = $user;
119 $connectionInfo['PWD'] = $password;
122 wfSuppressWarnings();
123 $this->mConn
= sqlsrv_connect( $server, $connectionInfo );
126 if ( $this->mConn
=== false ) {
127 throw new DBConnectionError( $this, $this->lastError() );
130 $this->mOpened
= true;
136 * Closes a database connection, if it is open
137 * Returns success, true if already closed
140 protected function closeConnection() {
141 return sqlsrv_close( $this->mConn
);
145 * @param bool|MssqlResultWrapper|resource $result
146 * @return bool|MssqlResultWrapper
148 public function resultObject( $result ) {
149 if ( empty( $result ) ) {
151 } elseif ( $result instanceof MssqlResultWrapper
) {
153 } elseif ( $result === true ) {
154 // Successful write query
157 return new MssqlResultWrapper( $this, $result );
163 * @return bool|MssqlResult
164 * @throws DBUnexpectedError
166 protected function doQuery( $sql ) {
167 if ( $this->debug() ) {
168 wfDebug( "SQL: [$sql]\n" );
172 // several extensions seem to think that all databases support limits
173 // via LIMIT N after the WHERE clause well, MSSQL uses SELECT TOP N,
174 // so to catch any of those extensions we'll do a quick check for a
175 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
176 // the limit clause and passes the result to $this->limitResult();
177 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
178 // massage LIMIT -> TopN
179 $sql = $this->LimitToTopN( $sql );
182 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
183 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
184 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
185 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
190 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
191 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
192 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
193 // strings make php throw a fatal error "Severe error translating Unicode"
194 if ( $this->mScrollableCursor
) {
195 $scrollArr = array( 'Scrollable' => SQLSRV_CURSOR_STATIC
);
197 $scrollArr = array();
200 if ( $this->mPrepareStatements
) {
201 // we do prepare + execute so we can get its field metadata for later usage if desired
202 $stmt = sqlsrv_prepare( $this->mConn
, $sql, array(), $scrollArr );
203 $success = sqlsrv_execute( $stmt );
205 $stmt = sqlsrv_query( $this->mConn
, $sql, array(), $scrollArr );
206 $success = (bool)$stmt;
209 if ( $this->mIgnoreDupKeyErrors
) {
210 // ignore duplicate key errors, but nothing else
211 // this emulates INSERT IGNORE in MySQL
212 if ( $success === false ) {
213 $errors = sqlsrv_errors( SQLSRV_ERR_ERRORS
);
216 foreach ( $errors as $err ) {
217 if ( $err['SQLSTATE'] == '23000' && $err['code'] == '2601' ) {
218 continue; // duplicate key error
219 } elseif ( $err['SQLSTATE'] == '01000' && $err['code'] == '3621' ) {
220 continue; // generic "the statement has been terminated" error
223 $success = false; // getting here means we got an error we weren't expecting
228 $this->mAffectedRows
= 0;
234 if ( $success === false ) {
237 // remember number of rows affected
238 $this->mAffectedRows
= sqlsrv_rows_affected( $stmt );
243 public function freeResult( $res ) {
244 if ( $res instanceof ResultWrapper
) {
248 sqlsrv_free_stmt( $res );
252 * @param MssqlResultWrapper $res
255 public function fetchObject( $res ) {
256 // $res is expected to be an instance of MssqlResultWrapper here
257 return $res->fetchObject();
261 * @param MssqlResultWrapper $res
264 public function fetchRow( $res ) {
265 return $res->fetchRow();
272 public function numRows( $res ) {
273 if ( $res instanceof ResultWrapper
) {
277 return sqlsrv_num_rows( $res );
284 public function numFields( $res ) {
285 if ( $res instanceof ResultWrapper
) {
289 return sqlsrv_num_fields( $res );
297 public function fieldName( $res, $n ) {
298 if ( $res instanceof ResultWrapper
) {
302 $metadata = sqlsrv_field_metadata( $res );
303 return $metadata[$n]['Name'];
307 * This must be called after nextSequenceVal
310 public function insertId() {
311 return $this->mInsertId
;
315 * @param MssqlResultWrapper $res
319 public function dataSeek( $res, $row ) {
320 return $res->seek( $row );
326 public function lastError() {
328 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
329 if ( $retErrors != null ) {
330 foreach ( $retErrors as $arrError ) {
331 $strRet .= $this->formatError( $arrError ) . "\n";
334 $strRet = "No errors found";
343 private function formatError( $err ) {
344 return '[SQLSTATE ' . $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
350 public function lastErrno() {
351 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
352 if ( $err !== null && isset( $err[0] ) ) {
353 return $err[0]['code'];
362 public function affectedRows() {
363 return $this->mAffectedRows
;
369 * @param mixed $table Array or string, table name(s) (prefix auto-added)
370 * @param mixed $vars Array or string, field name(s) to be retrieved
371 * @param mixed $conds Array or string, condition(s) for WHERE
372 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
373 * @param array $options Associative array of options (e.g.
374 * array('GROUP BY' => 'page_title')), see Database::makeSelectOptions
375 * code for list of supported stuff
376 * @param array $join_conds Associative array of table join conditions
377 * (optional) (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
378 * @return mixed Database result resource (feed to Database::fetchObject
379 * or whatever), or false on failure
381 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
382 $options = array(), $join_conds = array()
384 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
385 if ( isset( $options['EXPLAIN'] ) ) {
387 $this->mScrollableCursor
= false;
388 $this->mPrepareStatements
= false;
389 $this->query( "SET SHOWPLAN_ALL ON" );
390 $ret = $this->query( $sql, $fname );
391 $this->query( "SET SHOWPLAN_ALL OFF" );
392 } catch ( DBQueryError
$dqe ) {
393 if ( isset( $options['FOR COUNT'] ) ) {
394 // likely don't have privs for SHOWPLAN, so run a select count instead
395 $this->query( "SET SHOWPLAN_ALL OFF" );
396 unset( $options['EXPLAIN'] );
397 $ret = $this->select(
399 'COUNT(*) AS EstimateRows',
406 // someone actually wanted the query plan instead of an est row count
407 // let them know of the error
408 $this->mScrollableCursor
= true;
409 $this->mPrepareStatements
= true;
413 $this->mScrollableCursor
= true;
414 $this->mPrepareStatements
= true;
419 return $this->query( $sql, $fname );
425 * @param mixed $table Array or string, table name(s) (prefix auto-added)
426 * @param mixed $vars Array or string, field name(s) to be retrieved
427 * @param mixed $conds Array or string, condition(s) for WHERE
428 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
429 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
430 * see Database::makeSelectOptions code for list of supported stuff
431 * @param array $join_conds Associative array of table join conditions (optional)
432 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
433 * @return string The SQL text
435 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
436 $options = array(), $join_conds = array()
438 if ( isset( $options['EXPLAIN'] ) ) {
439 unset( $options['EXPLAIN'] );
442 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
444 // try to rewrite aggregations of bit columns (currently MAX and MIN)
445 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
446 $bitColumns = array();
447 if ( is_array( $table ) ) {
448 foreach ( $table as $t ) {
449 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
452 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
455 foreach ( $bitColumns as $col => $info ) {
457 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
458 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
460 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
467 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
470 $this->mScrollableCursor
= false;
472 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
473 } catch ( Exception
$e ) {
474 $this->mScrollableCursor
= true;
477 $this->mScrollableCursor
= true;
480 public function delete( $table, $conds, $fname = __METHOD__
) {
481 $this->mScrollableCursor
= false;
483 parent
::delete( $table, $conds, $fname );
484 } catch ( Exception
$e ) {
485 $this->mScrollableCursor
= true;
488 $this->mScrollableCursor
= true;
492 * Estimate rows in dataset
493 * Returns estimated count, based on SHOWPLAN_ALL output
494 * This is not necessarily an accurate estimate, so use sparingly
495 * Returns -1 if count cannot be found
496 * Takes same arguments as Database::select()
497 * @param string $table
498 * @param string $vars
499 * @param string $conds
500 * @param string $fname
501 * @param array $options
504 public function estimateRowCount( $table, $vars = '*', $conds = '',
505 $fname = __METHOD__
, $options = array()
507 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
508 $options['EXPLAIN'] = true;
509 $options['FOR COUNT'] = true;
510 $res = $this->select( $table, $vars, $conds, $fname, $options );
514 $row = $this->fetchRow( $res );
516 if ( isset( $row['EstimateRows'] ) ) {
517 $rows = $row['EstimateRows'];
525 * Returns information about an index
526 * If errors are explicitly ignored, returns NULL on failure
527 * @param string $table
528 * @param string $index
529 * @param string $fname
530 * @return array|bool|null
532 public function indexInfo( $table, $index, $fname = __METHOD__
) {
533 # This does not return the same info as MYSQL would, but that's OK
534 # because MediaWiki never uses the returned value except to check for
535 # the existance of indexes.
536 $sql = "sp_helpindex '" . $table . "'";
537 $res = $this->query( $sql, $fname );
543 foreach ( $res as $row ) {
544 if ( $row->index_name
== $index ) {
545 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
546 $cols = explode( ", ", $row->index_keys
);
547 foreach ( $cols as $col ) {
548 $row->Column_name
= trim( $col );
549 $result[] = clone $row;
551 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
552 $row->Non_unique
= 0;
553 $cols = explode( ", ", $row->index_keys
);
554 foreach ( $cols as $col ) {
555 $row->Column_name
= trim( $col );
556 $result[] = clone $row;
561 return empty( $result ) ?
false : $result;
565 * INSERT wrapper, inserts an array into a table
567 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
570 * Usually aborts on failure
571 * If errors are explicitly ignored, returns success
572 * @param string $table
573 * @param array $arrToInsert
574 * @param string $fname
575 * @param array $options
576 * @throws DBQueryError
579 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = array() ) {
580 # No rows to insert, easy just return now
581 if ( !count( $arrToInsert ) ) {
585 if ( !is_array( $options ) ) {
586 $options = array( $options );
589 $table = $this->tableName( $table );
591 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
592 $arrToInsert = array( 0 => $arrToInsert ); // make everything multi row compatible
595 // We know the table we're inserting into, get its identity column
597 // strip matching square brackets and the db/schema from table name
598 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
599 $tableRaw = array_pop( $tableRawArr );
600 $res = $this->doQuery(
601 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
602 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
604 if ( $res && sqlsrv_has_rows( $res ) ) {
605 // There is an identity for this table.
606 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
607 $identity = array_pop( $identityArr );
609 sqlsrv_free_stmt( $res );
611 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
612 $binaryColumns = $this->getBinaryColumns( $table );
614 foreach ( $arrToInsert as $a ) {
615 // start out with empty identity column, this is so we can return
616 // it as a result of the insert logic
619 $identityClause = '';
621 // if we have an identity column
624 foreach ( $a as $k => $v ) {
625 if ( $k == $identity ) {
626 if ( !is_null( $v ) ) {
627 // there is a value being passed to us,
628 // we need to turn on and off inserted identity
629 $sqlPre = "SET IDENTITY_INSERT $table ON;";
630 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
632 // we can't insert NULL into an identity column,
633 // so remove the column from the insert.
639 // we want to output an identity column as result
640 $identityClause = "OUTPUT INSERTED.$identity ";
643 $keys = array_keys( $a );
645 // INSERT IGNORE is not supported by SQL Server
646 // remove IGNORE from options list and set ignore flag to true
647 $ignoreClause = false;
648 if ( in_array( 'IGNORE', $options ) ) {
649 $options = array_diff( $options, array( 'IGNORE' ) );
650 $this->mIgnoreDupKeyErrors
= true;
653 // Build the actual query
654 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
655 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
658 foreach ( $a as $key => $value ) {
659 if ( isset( $binaryColumns[$key] ) ) {
660 $value = new MssqlBlob( $value );
667 if ( is_null( $value ) ) {
669 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
670 if ( is_object( $value ) && $value instanceof Blob
) {
671 $sql .= $this->addQuotes( $value );
673 $sql .= $this->addQuotes( serialize( $value ) );
676 $sql .= $this->addQuotes( $value );
679 $sql .= ')' . $sqlPost;
682 $this->mScrollableCursor
= false;
684 $ret = $this->query( $sql );
685 } catch ( Exception
$e ) {
686 $this->mScrollableCursor
= true;
687 $this->mIgnoreDupKeyErrors
= false;
690 $this->mScrollableCursor
= true;
691 $this->mIgnoreDupKeyErrors
= false;
693 if ( !is_null( $identity ) ) {
694 // then we want to get the identity column value we were assigned and save it off
695 $row = $ret->fetchObject();
696 $this->mInsertId
= $row->$identity;
704 * INSERT SELECT wrapper
705 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
706 * Source items may be literals rather than field names, but strings should
707 * be quoted with Database::addQuotes().
708 * @param string $destTable
709 * @param array|string $srcTable May be an array of tables.
710 * @param array $varMap
711 * @param array $conds May be "*" to copy the whole table.
712 * @param string $fname
713 * @param array $insertOptions
714 * @param array $selectOptions
715 * @throws DBQueryError
716 * @return null|ResultWrapper
718 public function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
719 $insertOptions = array(), $selectOptions = array()
721 $this->mScrollableCursor
= false;
723 $ret = parent
::insertSelect(
732 } catch ( Exception
$e ) {
733 $this->mScrollableCursor
= true;
736 $this->mScrollableCursor
= true;
742 * UPDATE wrapper. Takes a condition array and a SET array.
744 * @param string $table name of the table to UPDATE. This will be passed through
745 * DatabaseBase::tableName().
747 * @param array $values An array of values to SET. For each array element,
748 * the key gives the field name, and the value gives the data
749 * to set that field to. The data will be quoted by
750 * DatabaseBase::addQuotes().
752 * @param array $conds An array of conditions (WHERE). See
753 * DatabaseBase::select() for the details of the format of
754 * condition arrays. Use '*' to update all rows.
756 * @param string $fname The function name of the caller (from __METHOD__),
757 * for logging and profiling.
759 * @param array $options An array of UPDATE options, can be:
760 * - IGNORE: Ignore unique key conflicts
761 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
764 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
765 $table = $this->tableName( $table );
766 $binaryColumns = $this->getBinaryColumns( $table );
768 $opts = $this->makeUpdateOptions( $options );
769 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
771 if ( $conds !== array() && $conds !== '*' ) {
772 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
775 $this->mScrollableCursor
= false;
777 $ret = $this->query( $sql );
778 } catch ( Exception
$e ) {
779 $this->mScrollableCursor
= true;
782 $this->mScrollableCursor
= true;
787 * Makes an encoded list of strings from an array
788 * @param array $a containing the data
789 * @param int $mode Constant
790 * - LIST_COMMA: comma separated, no field names
791 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
792 * the documentation for $conds in DatabaseBase::select().
793 * - LIST_OR: ORed WHERE clause (without the WHERE)
794 * - LIST_SET: comma separated with field names, like a SET clause
795 * - LIST_NAMES: comma separated field names
796 * @param array $binaryColumns Contains a list of column names that are binary types
797 * This is a custom parameter only present for MS SQL.
799 * @throws MWException|DBUnexpectedError
802 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = array() ) {
803 if ( !is_array( $a ) ) {
804 throw new DBUnexpectedError( $this,
805 'DatabaseBase::makeList called with incorrect parameters' );
811 foreach ( $a as $field => $value ) {
812 if ( $mode != LIST_NAMES
&& isset( $binaryColumns[$field] ) ) {
813 if ( is_array( $value ) ) {
814 foreach ( $value as &$v ) {
815 $v = new MssqlBlob( $v );
818 $value = new MssqlBlob( $value );
823 if ( $mode == LIST_AND
) {
825 } elseif ( $mode == LIST_OR
) {
834 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
836 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
838 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
839 if ( count( $value ) == 0 ) {
840 throw new MWException( __METHOD__
. ": empty input for field $field" );
841 } elseif ( count( $value ) == 1 ) {
842 // Special-case single values, as IN isn't terribly efficient
843 // Don't necessarily assume the single key is 0; we don't
844 // enforce linear numeric ordering on other arrays here.
845 $value = array_values( $value );
846 $list .= $field . " = " . $this->addQuotes( $value[0] );
848 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
850 } elseif ( $value === null ) {
851 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
852 $list .= "$field IS ";
853 } elseif ( $mode == LIST_SET
) {
854 $list .= "$field = ";
858 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
859 $list .= "$field = ";
861 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
869 * @param string $table
870 * @param string $field
871 * @return int Returns the size of a text field, or -1 for "unlimited"
873 public function textFieldSize( $table, $field ) {
874 $table = $this->tableName( $table );
875 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
876 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
877 $res = $this->query( $sql );
878 $row = $this->fetchRow( $res );
880 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
881 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
888 * Construct a LIMIT query with optional offset
889 * This is used for query pages
891 * @param string $sql SQL query we will append the limit too
892 * @param int $limit The SQL limit
893 * @param bool|int $offset The SQL offset (default false)
894 * @return array|string
896 public function limitResult( $sql, $limit, $offset = false ) {
897 if ( $offset === false ||
$offset == 0 ) {
898 if ( strpos( $sql, "SELECT" ) === false ) {
899 return "TOP {$limit} " . $sql;
901 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
902 'SELECT$1 TOP ' . $limit, $sql, 1 );
905 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
906 $select = $orderby = array();
907 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
908 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
909 $overOrder = $postOrder = '';
910 $first = $offset +
1;
911 $last = $offset +
$limit;
912 $sub1 = 'sub_' . $this->mSubqueryId
;
913 $sub2 = 'sub_' . ( $this->mSubqueryId +
1 );
914 $this->mSubqueryId +
= 2;
917 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
921 $overOrder = 'ORDER BY 1';
923 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
924 // don't need to strip it out if we're using a FOR XML clause
925 $sql = str_replace( $orderby[1], '', $sql );
927 $overOrder = $orderby[1];
928 $postOrder = ' ' . $overOrder;
930 $sql = "SELECT {$select[1]}
932 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
933 FROM ({$sql}) {$sub1}
935 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
942 * If there is a limit clause, parse it, strip it, and pass the remaining
943 * SQL through limitResult() with the appropriate parameters. Not the
944 * prettiest solution, but better than building a whole new parser. This
945 * exists becase there are still too many extensions that don't use dynamic
949 * @return array|mixed|string
951 public function LimitToTopN( $sql ) {
952 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
953 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
954 if ( preg_match( $pattern, $sql, $matches ) ) {
955 // row_count = $matches[4]
956 $row_count = $matches[4];
957 // offset = $matches[3] OR $matches[6]
958 $offset = $matches[3] or
959 $offset = $matches[6] or
962 // strip the matching LIMIT clause out
963 $sql = str_replace( $matches[0], '', $sql );
965 return $this->limitResult( $sql, $row_count, $offset );
972 * @return string Wikitext of a link to the server software's web site
974 public function getSoftwareLink() {
975 return "[{{int:version-db-mssql-url}} MS SQL Server]";
979 * @return string Version information from the database
981 public function getServerVersion() {
982 $server_info = sqlsrv_server_info( $this->mConn
);
984 if ( isset( $server_info['SQLServerVersion'] ) ) {
985 $version = $server_info['SQLServerVersion'];
992 * @param string $table
993 * @param string $fname
994 * @param bool $schema
997 public function tableExists( $table, $fname = __METHOD__
, $schema = false ) {
998 $res = sqlsrv_query( $this->mConn
, "SELECT * FROM information_schema.tables
999 WHERE table_type='BASE TABLE' AND table_name = '$table'" );
1000 if ( $res === false ) {
1001 print "Error in tableExists query: " . $this->lastError();
1005 if ( sqlsrv_fetch( $res ) ) {
1013 * Query whether a given column exists in the mediawiki schema
1014 * @param string $table
1015 * @param string $field
1016 * @param string $fname
1019 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1020 $table = $this->tableName( $table );
1021 $res = sqlsrv_query( $this->mConn
, "SELECT DATA_TYPE FROM INFORMATION_SCHEMA.Columns
1022 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1023 if ( $res === false ) {
1024 print "Error in fieldExists query: " . $this->lastError();
1028 if ( sqlsrv_fetch( $res ) ) {
1035 public function fieldInfo( $table, $field ) {
1036 $table = $this->tableName( $table );
1037 $res = sqlsrv_query( $this->mConn
, "SELECT * FROM INFORMATION_SCHEMA.Columns
1038 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1039 if ( $res === false ) {
1040 print "Error in fieldInfo query: " . $this->lastError();
1044 $meta = $this->fetchRow( $res );
1046 return new MssqlField( $meta );
1053 * Begin a transaction, committing any previously open transaction
1055 protected function doBegin( $fname = __METHOD__
) {
1056 sqlsrv_begin_transaction( $this->mConn
);
1057 $this->mTrxLevel
= 1;
1063 protected function doCommit( $fname = __METHOD__
) {
1064 sqlsrv_commit( $this->mConn
);
1065 $this->mTrxLevel
= 0;
1069 * Rollback a transaction.
1070 * No-op on non-transactional databases.
1072 protected function doRollback( $fname = __METHOD__
) {
1073 sqlsrv_rollback( $this->mConn
);
1074 $this->mTrxLevel
= 0;
1078 * Escapes a identifier for use inm SQL.
1079 * Throws an exception if it is invalid.
1080 * Reference: http://msdn.microsoft.com/en-us/library/aa224033%28v=SQL.80%29.aspx
1081 * @param string $identifier
1082 * @throws MWException
1085 private function escapeIdentifier( $identifier ) {
1086 if ( strlen( $identifier ) == 0 ) {
1087 throw new MWException( "An identifier must not be empty" );
1089 if ( strlen( $identifier ) > 128 ) {
1090 throw new MWException( "The identifier '$identifier' is too long (max. 128)" );
1092 if ( ( strpos( $identifier, '[' ) !== false )
1093 ||
( strpos( $identifier, ']' ) !== false )
1095 // It may be allowed if you quoted with double quotation marks, but
1096 // that would break if QUOTED_IDENTIFIER is OFF
1097 throw new MWException( "Square brackets are not allowed in '$identifier'" );
1100 return "[$identifier]";
1107 public function strencode( $s ) { # Should not be called by us
1108 return str_replace( "'", "''", $s );
1115 public function addQuotes( $s ) {
1116 if ( $s instanceof MssqlBlob
) {
1118 } elseif ( $s instanceof Blob
) {
1119 // this shouldn't really ever be called, but it's here if needed
1120 // (and will quite possibly make the SQL error out)
1121 $blob = new MssqlBlob( $s->fetch() );
1122 return $blob->fetch();
1124 if ( is_bool( $s ) ) {
1127 return parent
::addQuotes( $s );
1135 public function addIdentifierQuotes( $s ) {
1136 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1137 return '[' . $s . ']';
1141 * @param string $name
1144 public function isQuotedIdentifier( $name ) {
1145 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1152 public function selectDB( $db ) {
1154 $this->mDBname
= $db;
1155 $this->query( "USE $db" );
1157 } catch ( Exception
$e ) {
1163 * @param array $options an associative array of options to be turned into
1164 * an SQL query, valid keys are listed in the function.
1167 public function makeSelectOptions( $options ) {
1171 $noKeyOptions = array();
1172 foreach ( $options as $key => $option ) {
1173 if ( is_numeric( $key ) ) {
1174 $noKeyOptions[$option] = true;
1178 $tailOpts .= $this->makeGroupByWithHaving( $options );
1180 $tailOpts .= $this->makeOrderBy( $options );
1182 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1183 $startOpts .= 'DISTINCT';
1186 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1187 // used in group concat field emulation
1188 $tailOpts .= " FOR XML PATH('')";
1191 // we want this to be compatible with the output of parent::makeSelectOptions()
1192 return array( $startOpts, '', $tailOpts, '' );
1196 * Get the type of the DBMS, as it appears in $wgDBtype.
1199 public function getType() {
1204 * @param array $stringList
1207 public function buildConcat( $stringList ) {
1208 return implode( ' + ', $stringList );
1212 * Build a GROUP_CONCAT or equivalent statement for a query.
1213 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1215 * This is useful for combining a field for several rows into a single string.
1216 * NULL values will not appear in the output, duplicated values will appear,
1217 * and the resulting delimiter-separated values have no defined sort order.
1218 * Code using the results may need to use the PHP unique() or sort() methods.
1220 * @param string $delim Glue to bind the results together
1221 * @param string|array $table Table name
1222 * @param string $field Field name
1223 * @param string|array $conds Conditions
1224 * @param string|array $join_conds Join conditions
1225 * @return String SQL text
1228 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1229 $join_conds = array()
1231 $gcsq = 'gcsq_' . $this->mSubqueryId
;
1232 $this->mSubqueryId++
;
1234 $delimLen = strlen( $delim );
1235 $fld = "{$field} + {$this->addQuotes( $delim )}";
1236 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1237 . $this->selectSQLText( $table, $fld, $conds, null, array( 'FOR XML' ), $join_conds )
1238 . ") {$gcsq} ({$field}))";
1246 public function getSearchEngine() {
1247 return "SearchMssql";
1251 * Returns an associative array for fields that are of type varbinary, binary, or image
1252 * $table can be either a raw table name or passed through tableName() first
1253 * @param string $table
1256 private function getBinaryColumns( $table ) {
1257 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1258 $tableRaw = array_pop( $tableRawArr );
1260 if ( $this->mBinaryColumnCache
=== null ) {
1261 $this->populateColumnCaches();
1264 return isset( $this->mBinaryColumnCache
[$tableRaw] )
1265 ?
$this->mBinaryColumnCache
[$tableRaw]
1270 * @param string $table
1273 private function getBitColumns( $table ) {
1274 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1275 $tableRaw = array_pop( $tableRawArr );
1277 if ( $this->mBitColumnCache
=== null ) {
1278 $this->populateColumnCaches();
1281 return isset( $this->mBitColumnCache
[$tableRaw] )
1282 ?
$this->mBitColumnCache
[$tableRaw]
1289 private function populateColumnCaches() {
1290 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1292 'TABLE_CATALOG' => $this->mDBname
,
1293 'TABLE_SCHEMA' => $this->mSchema
,
1294 'DATA_TYPE' => array( 'varbinary', 'binary', 'image', 'bit' )
1297 $this->mBinaryColumnCache
= array();
1298 $this->mBitColumnCache
= array();
1299 foreach ( $res as $row ) {
1300 if ( $row->DATA_TYPE
== 'bit' ) {
1301 $this->mBitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1303 $this->mBinaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1309 * @param string $name
1310 * @param string $format
1313 function tableName( $name, $format = 'quoted' ) {
1314 # Replace reserved words with better ones
1317 return $this->realTableName( 'mwuser', $format );
1319 return $this->realTableName( $name, $format );
1324 * call this instead of tableName() in the updater when renaming tables
1325 * @param string $name
1326 * @param string $format
1329 function realTableName( $name, $format = 'quoted' ) {
1330 return parent
::tableName( $name, $format );
1334 * Called in the installer and updater.
1335 * Probably doesn't need to be called anywhere else in the codebase.
1336 * @param bool|null $value
1339 public function prepareStatements( $value = null ) {
1340 return wfSetVar( $this->mPrepareStatements
, $value );
1344 * Called in the installer and updater.
1345 * Probably doesn't need to be called anywhere else in the codebase.
1346 * @param bool|null $value
1349 public function scrollableCursor( $value = null ) {
1350 return wfSetVar( $this->mScrollableCursor
, $value );
1352 } // end DatabaseMssql class
1359 class MssqlField
implements Field
{
1360 private $name, $tableName, $default, $max_length, $nullable, $type;
1362 function __construct( $info ) {
1363 $this->name
= $info['COLUMN_NAME'];
1364 $this->tableName
= $info['TABLE_NAME'];
1365 $this->default = $info['COLUMN_DEFAULT'];
1366 $this->max_length
= $info['CHARACTER_MAXIMUM_LENGTH'];
1367 $this->nullable
= !( strtolower( $info['IS_NULLABLE'] ) == 'no' );
1368 $this->type
= $info['DATA_TYPE'];
1375 function tableName() {
1376 return $this->tableName
;
1379 function defaultValue() {
1380 return $this->default;
1383 function maxLength() {
1384 return $this->max_length
;
1387 function isNullable() {
1388 return $this->nullable
;
1396 class MssqlBlob
extends Blob
{
1397 public function __construct( $data ) {
1398 if ( $data instanceof MssqlBlob
) {
1400 } elseif ( $data instanceof Blob
) {
1401 $this->mData
= $data->fetch();
1402 } elseif ( is_array( $data ) && is_object( $data ) ) {
1403 $this->mData
= serialize( $data );
1405 $this->mData
= $data;
1410 * Returns an unquoted hex representation of a binary string
1411 * for insertion into varbinary-type fields
1414 public function fetch() {
1415 if ( $this->mData
=== null ) {
1420 $dataLength = strlen( $this->mData
);
1421 for ( $i = 0; $i < $dataLength; $i++
) {
1422 $ret .= bin2hex( pack( 'C', ord( $this->mData
[$i] ) ) );
1429 class MssqlResultWrapper
extends ResultWrapper
{
1430 private $mSeekTo = null;
1433 * @return stdClass|bool
1435 public function fetchObject() {
1436 $res = $this->result
;
1438 if ( $this->mSeekTo
!== null ) {
1439 $result = sqlsrv_fetch_object( $res, 'stdClass', array(),
1440 SQLSRV_SCROLL_ABSOLUTE
, $this->mSeekTo
);
1441 $this->mSeekTo
= null;
1443 $result = sqlsrv_fetch_object( $res );
1446 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1447 if ( $result === null ) {
1455 * @return array|bool
1457 public function fetchRow() {
1458 $res = $this->result
;
1460 if ( $this->mSeekTo
!== null ) {
1461 $result = sqlsrv_fetch_array( $res, SQLSRV_FETCH_BOTH
,
1462 SQLSRV_SCROLL_ABSOLUTE
, $this->mSeekTo
);
1463 $this->mSeekTo
= null;
1465 $result = sqlsrv_fetch_array( $res );
1468 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1469 if ( $result === null ) {
1480 public function seek( $row ) {
1481 $res = $this->result
;
1484 $numRows = $this->db
->numRows( $res );
1485 $row = intval( $row );
1487 if ( $numRows === 0 ) {
1489 } elseif ( $row < 0 ||
$row > $numRows - 1 ) {
1493 // Unlike MySQL, the seek actually happens on the next access
1494 $this->mSeekTo
= $row;