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 Database
{
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;
41 protected $mIgnoreErrors = [];
45 public function cascadingDeletes() {
49 public function cleanupTriggers() {
53 public function strictIPs() {
57 public function realTimestamps() {
61 public function implicitGroupby() {
65 public function implicitOrderby() {
69 public function functionalIndexes() {
73 public function unionSupportsOrderAndLimit() {
78 * Usually aborts on failure
79 * @param string $server
81 * @param string $password
82 * @param string $dbName
83 * @throws DBConnectionError
84 * @return bool|resource|null
86 public function open( $server, $user, $password, $dbName ) {
87 # Test for driver support, to avoid suppressed fatal error
88 if ( !function_exists( 'sqlsrv_connect' ) ) {
89 throw new DBConnectionError(
91 "Microsoft SQL Server Native (sqlsrv) functions missing.
92 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
96 global $wgDBport, $wgDBWindowsAuthentication;
98 # e.g. the class is being loaded
99 if ( !strlen( $user ) ) {
104 $this->mServer
= $server;
105 $this->mPort
= $wgDBport;
106 $this->mUser
= $user;
107 $this->mPassword
= $password;
108 $this->mDBname
= $dbName;
110 $connectionInfo = [];
113 $connectionInfo['Database'] = $dbName;
116 // Decide which auth scenerio to use
117 // if we are using Windows auth, don't add credentials to $connectionInfo
118 if ( !$wgDBWindowsAuthentication ) {
119 $connectionInfo['UID'] = $user;
120 $connectionInfo['PWD'] = $password;
123 MediaWiki\
suppressWarnings();
124 $this->mConn
= sqlsrv_connect( $server, $connectionInfo );
125 MediaWiki\restoreWarnings
();
127 if ( $this->mConn
=== false ) {
128 throw new DBConnectionError( $this, $this->lastError() );
131 $this->mOpened
= true;
137 * Closes a database connection, if it is open
138 * Returns success, true if already closed
141 protected function closeConnection() {
142 return sqlsrv_close( $this->mConn
);
146 * @param bool|MssqlResultWrapper|resource $result
147 * @return bool|MssqlResultWrapper
149 protected function resultObject( $result ) {
152 } elseif ( $result instanceof MssqlResultWrapper
) {
154 } elseif ( $result === true ) {
155 // Successful write query
158 return new MssqlResultWrapper( $this, $result );
164 * @return bool|MssqlResult
165 * @throws DBUnexpectedError
167 protected function doQuery( $sql ) {
168 if ( $this->debug() ) {
169 wfDebug( "SQL: [$sql]\n" );
173 // several extensions seem to think that all databases support limits
174 // via LIMIT N after the WHERE clause well, MSSQL uses SELECT TOP N,
175 // so to catch any of those extensions we'll do a quick check for a
176 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
177 // the limit clause and passes the result to $this->limitResult();
178 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
179 // massage LIMIT -> TopN
180 $sql = $this->LimitToTopN( $sql );
183 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
184 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
185 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
186 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
191 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
192 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
193 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
194 // strings make php throw a fatal error "Severe error translating Unicode"
195 if ( $this->mScrollableCursor
) {
196 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
201 if ( $this->mPrepareStatements
) {
202 // we do prepare + execute so we can get its field metadata for later usage if desired
203 $stmt = sqlsrv_prepare( $this->mConn
, $sql, [], $scrollArr );
204 $success = sqlsrv_execute( $stmt );
206 $stmt = sqlsrv_query( $this->mConn
, $sql, [], $scrollArr );
207 $success = (bool)$stmt;
210 // make a copy so that anything we add below does not get reflected in future queries
211 $ignoreErrors = $this->mIgnoreErrors
;
213 if ( $this->mIgnoreDupKeyErrors
) {
214 // ignore duplicate key errors
215 // this emulates INSERT IGNORE in MySQL
216 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
217 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
218 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
221 if ( $success === false ) {
222 $errors = sqlsrv_errors();
225 foreach ( $errors as $err ) {
226 if ( !in_array( $err['code'], $ignoreErrors ) ) {
232 if ( $success === false ) {
236 // remember number of rows affected
237 $this->mAffectedRows
= sqlsrv_rows_affected( $stmt );
242 public function freeResult( $res ) {
243 if ( $res instanceof ResultWrapper
) {
247 sqlsrv_free_stmt( $res );
251 * @param MssqlResultWrapper $res
254 public function fetchObject( $res ) {
255 // $res is expected to be an instance of MssqlResultWrapper here
256 return $res->fetchObject();
260 * @param MssqlResultWrapper $res
263 public function fetchRow( $res ) {
264 return $res->fetchRow();
271 public function numRows( $res ) {
272 if ( $res instanceof ResultWrapper
) {
276 $ret = sqlsrv_num_rows( $res );
278 if ( $ret === false ) {
279 // we cannot get an amount of rows from this cursor type
280 // has_rows returns bool true/false if the result has rows
281 $ret = (int)sqlsrv_has_rows( $res );
291 public function numFields( $res ) {
292 if ( $res instanceof ResultWrapper
) {
296 return sqlsrv_num_fields( $res );
304 public function fieldName( $res, $n ) {
305 if ( $res instanceof ResultWrapper
) {
309 return sqlsrv_field_metadata( $res )[$n]['Name'];
313 * This must be called after nextSequenceVal
316 public function insertId() {
317 return $this->mInsertId
;
321 * @param MssqlResultWrapper $res
325 public function dataSeek( $res, $row ) {
326 return $res->seek( $row );
332 public function lastError() {
334 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
335 if ( $retErrors != null ) {
336 foreach ( $retErrors as $arrError ) {
337 $strRet .= $this->formatError( $arrError ) . "\n";
340 $strRet = "No errors found";
350 private function formatError( $err ) {
351 return '[SQLSTATE ' . $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
357 public function lastErrno() {
358 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
359 if ( $err !== null && isset( $err[0] ) ) {
360 return $err[0]['code'];
369 public function affectedRows() {
370 return $this->mAffectedRows
;
376 * @param mixed $table Array or string, table name(s) (prefix auto-added)
377 * @param mixed $vars Array or string, field name(s) to be retrieved
378 * @param mixed $conds Array or string, condition(s) for WHERE
379 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
380 * @param array $options Associative array of options (e.g.
381 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
382 * code for list of supported stuff
383 * @param array $join_conds Associative array of table join conditions
384 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
385 * @return mixed Database result resource (feed to Database::fetchObject
386 * or whatever), or false on failure
387 * @throws DBQueryError
388 * @throws DBUnexpectedError
391 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
392 $options = [], $join_conds = []
394 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
395 if ( isset( $options['EXPLAIN'] ) ) {
397 $this->mScrollableCursor
= false;
398 $this->mPrepareStatements
= false;
399 $this->query( "SET SHOWPLAN_ALL ON" );
400 $ret = $this->query( $sql, $fname );
401 $this->query( "SET SHOWPLAN_ALL OFF" );
402 } catch ( DBQueryError
$dqe ) {
403 if ( isset( $options['FOR COUNT'] ) ) {
404 // likely don't have privs for SHOWPLAN, so run a select count instead
405 $this->query( "SET SHOWPLAN_ALL OFF" );
406 unset( $options['EXPLAIN'] );
407 $ret = $this->select(
409 'COUNT(*) AS EstimateRows',
416 // someone actually wanted the query plan instead of an est row count
417 // let them know of the error
418 $this->mScrollableCursor
= true;
419 $this->mPrepareStatements
= true;
423 $this->mScrollableCursor
= true;
424 $this->mPrepareStatements
= true;
427 return $this->query( $sql, $fname );
433 * @param mixed $table Array or string, table name(s) (prefix auto-added)
434 * @param mixed $vars Array or string, field name(s) to be retrieved
435 * @param mixed $conds Array or string, condition(s) for WHERE
436 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
437 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
438 * see Database::makeSelectOptions code for list of supported stuff
439 * @param array $join_conds Associative array of table join conditions (optional)
440 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
441 * @return string The SQL text
443 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
444 $options = [], $join_conds = []
446 if ( isset( $options['EXPLAIN'] ) ) {
447 unset( $options['EXPLAIN'] );
450 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
452 // try to rewrite aggregations of bit columns (currently MAX and MIN)
453 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
455 if ( is_array( $table ) ) {
456 foreach ( $table as $t ) {
457 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
460 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
463 foreach ( $bitColumns as $col => $info ) {
465 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
466 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
468 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
475 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
478 $this->mScrollableCursor
= false;
480 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
481 } catch ( Exception
$e ) {
482 $this->mScrollableCursor
= true;
485 $this->mScrollableCursor
= true;
488 public function delete( $table, $conds, $fname = __METHOD__
) {
489 $this->mScrollableCursor
= false;
491 parent
::delete( $table, $conds, $fname );
492 } catch ( Exception
$e ) {
493 $this->mScrollableCursor
= true;
496 $this->mScrollableCursor
= true;
500 * Estimate rows in dataset
501 * Returns estimated count, based on SHOWPLAN_ALL output
502 * This is not necessarily an accurate estimate, so use sparingly
503 * Returns -1 if count cannot be found
504 * Takes same arguments as Database::select()
505 * @param string $table
506 * @param string $vars
507 * @param string $conds
508 * @param string $fname
509 * @param array $options
512 public function estimateRowCount( $table, $vars = '*', $conds = '',
513 $fname = __METHOD__
, $options = []
515 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
516 $options['EXPLAIN'] = true;
517 $options['FOR COUNT'] = true;
518 $res = $this->select( $table, $vars, $conds, $fname, $options );
522 $row = $this->fetchRow( $res );
524 if ( isset( $row['EstimateRows'] ) ) {
525 $rows = (int)$row['EstimateRows'];
533 * Returns information about an index
534 * If errors are explicitly ignored, returns NULL on failure
535 * @param string $table
536 * @param string $index
537 * @param string $fname
538 * @return array|bool|null
540 public function indexInfo( $table, $index, $fname = __METHOD__
) {
541 # This does not return the same info as MYSQL would, but that's OK
542 # because MediaWiki never uses the returned value except to check for
543 # the existance of indexes.
544 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
545 $res = $this->query( $sql, $fname );
552 foreach ( $res as $row ) {
553 if ( $row->index_name
== $index ) {
554 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
555 $cols = explode( ", ", $row->index_keys
);
556 foreach ( $cols as $col ) {
557 $row->Column_name
= trim( $col );
558 $result[] = clone $row;
560 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
561 $row->Non_unique
= 0;
562 $cols = explode( ", ", $row->index_keys
);
563 foreach ( $cols as $col ) {
564 $row->Column_name
= trim( $col );
565 $result[] = clone $row;
570 return empty( $result ) ?
false : $result;
574 * INSERT wrapper, inserts an array into a table
576 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
579 * Usually aborts on failure
580 * If errors are explicitly ignored, returns success
581 * @param string $table
582 * @param array $arrToInsert
583 * @param string $fname
584 * @param array $options
588 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
589 # No rows to insert, easy just return now
590 if ( !count( $arrToInsert ) ) {
594 if ( !is_array( $options ) ) {
595 $options = [ $options ];
598 $table = $this->tableName( $table );
600 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
601 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
604 // We know the table we're inserting into, get its identity column
606 // strip matching square brackets and the db/schema from table name
607 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
608 $tableRaw = array_pop( $tableRawArr );
609 $res = $this->doQuery(
610 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
611 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
613 if ( $res && sqlsrv_has_rows( $res ) ) {
614 // There is an identity for this table.
615 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
616 $identity = array_pop( $identityArr );
618 sqlsrv_free_stmt( $res );
620 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
621 $binaryColumns = $this->getBinaryColumns( $table );
623 // INSERT IGNORE is not supported by SQL Server
624 // remove IGNORE from options list and set ignore flag to true
625 if ( in_array( 'IGNORE', $options ) ) {
626 $options = array_diff( $options, [ 'IGNORE' ] );
627 $this->mIgnoreDupKeyErrors
= true;
630 foreach ( $arrToInsert as $a ) {
631 // start out with empty identity column, this is so we can return
632 // it as a result of the insert logic
635 $identityClause = '';
637 // if we have an identity column
640 foreach ( $a as $k => $v ) {
641 if ( $k == $identity ) {
642 if ( !is_null( $v ) ) {
643 // there is a value being passed to us,
644 // we need to turn on and off inserted identity
645 $sqlPre = "SET IDENTITY_INSERT $table ON;";
646 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
648 // we can't insert NULL into an identity column,
649 // so remove the column from the insert.
655 // we want to output an identity column as result
656 $identityClause = "OUTPUT INSERTED.$identity ";
659 $keys = array_keys( $a );
661 // Build the actual query
662 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
663 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
666 foreach ( $a as $key => $value ) {
667 if ( isset( $binaryColumns[$key] ) ) {
668 $value = new MssqlBlob( $value );
675 if ( is_null( $value ) ) {
677 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
678 if ( is_object( $value ) && $value instanceof Blob
) {
679 $sql .= $this->addQuotes( $value );
681 $sql .= $this->addQuotes( serialize( $value ) );
684 $sql .= $this->addQuotes( $value );
687 $sql .= ')' . $sqlPost;
690 $this->mScrollableCursor
= false;
692 $ret = $this->query( $sql );
693 } catch ( Exception
$e ) {
694 $this->mScrollableCursor
= true;
695 $this->mIgnoreDupKeyErrors
= false;
698 $this->mScrollableCursor
= true;
700 if ( !is_null( $identity ) ) {
701 // then we want to get the identity column value we were assigned and save it off
702 $row = $ret->fetchObject();
703 if ( is_object( $row ) ) {
704 $this->mInsertId
= $row->$identity;
706 // it seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is used
707 // if we got an identity back, we know for sure a row was affected, so adjust that here
708 if ( $this->mAffectedRows
== -1 ) {
709 $this->mAffectedRows
= 1;
714 $this->mIgnoreDupKeyErrors
= false;
719 * INSERT SELECT wrapper
720 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
721 * Source items may be literals rather than field names, but strings should
722 * be quoted with Database::addQuotes().
723 * @param string $destTable
724 * @param array|string $srcTable May be an array of tables.
725 * @param array $varMap
726 * @param array $conds May be "*" to copy the whole table.
727 * @param string $fname
728 * @param array $insertOptions
729 * @param array $selectOptions
730 * @return null|ResultWrapper
733 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
734 $insertOptions = [], $selectOptions = []
736 $this->mScrollableCursor
= false;
738 $ret = parent
::nativeInsertSelect(
747 } catch ( Exception
$e ) {
748 $this->mScrollableCursor
= true;
751 $this->mScrollableCursor
= true;
757 * UPDATE wrapper. Takes a condition array and a SET array.
759 * @param string $table Name of the table to UPDATE. This will be passed through
760 * DatabaseBase::tableName().
762 * @param array $values An array of values to SET. For each array element,
763 * the key gives the field name, and the value gives the data
764 * to set that field to. The data will be quoted by
765 * DatabaseBase::addQuotes().
767 * @param array $conds An array of conditions (WHERE). See
768 * DatabaseBase::select() for the details of the format of
769 * condition arrays. Use '*' to update all rows.
771 * @param string $fname The function name of the caller (from __METHOD__),
772 * for logging and profiling.
774 * @param array $options An array of UPDATE options, can be:
775 * - IGNORE: Ignore unique key conflicts
776 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
778 * @throws DBUnexpectedError
780 * @throws MWException
782 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
783 $table = $this->tableName( $table );
784 $binaryColumns = $this->getBinaryColumns( $table );
786 $opts = $this->makeUpdateOptions( $options );
787 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
789 if ( $conds !== [] && $conds !== '*' ) {
790 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
793 $this->mScrollableCursor
= false;
795 $ret = $this->query( $sql );
796 } catch ( Exception
$e ) {
797 $this->mScrollableCursor
= true;
800 $this->mScrollableCursor
= true;
805 * Makes an encoded list of strings from an array
806 * @param array $a Containing the data
807 * @param int $mode Constant
808 * - LIST_COMMA: comma separated, no field names
809 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
810 * the documentation for $conds in DatabaseBase::select().
811 * - LIST_OR: ORed WHERE clause (without the WHERE)
812 * - LIST_SET: comma separated with field names, like a SET clause
813 * - LIST_NAMES: comma separated field names
814 * @param array $binaryColumns Contains a list of column names that are binary types
815 * This is a custom parameter only present for MS SQL.
817 * @throws MWException|DBUnexpectedError
820 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
821 if ( !is_array( $a ) ) {
822 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
825 if ( $mode != LIST_NAMES
) {
826 // In MS SQL, values need to be specially encoded when they are
827 // inserted into binary fields. Perform this necessary encoding
828 // for the specified set of columns.
829 foreach ( array_keys( $a ) as $field ) {
830 if ( !isset( $binaryColumns[$field] ) ) {
834 if ( is_array( $a[$field] ) ) {
835 foreach ( $a[$field] as &$v ) {
836 $v = new MssqlBlob( $v );
840 $a[$field] = new MssqlBlob( $a[$field] );
845 return parent
::makeList( $a, $mode );
849 * @param string $table
850 * @param string $field
851 * @return int Returns the size of a text field, or -1 for "unlimited"
853 public function textFieldSize( $table, $field ) {
854 $table = $this->tableName( $table );
855 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
856 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
857 $res = $this->query( $sql );
858 $row = $this->fetchRow( $res );
860 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
861 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
868 * Construct a LIMIT query with optional offset
869 * This is used for query pages
871 * @param string $sql SQL query we will append the limit too
872 * @param int $limit The SQL limit
873 * @param bool|int $offset The SQL offset (default false)
874 * @return array|string
875 * @throws DBUnexpectedError
877 public function limitResult( $sql, $limit, $offset = false ) {
878 if ( $offset === false ||
$offset == 0 ) {
879 if ( strpos( $sql, "SELECT" ) === false ) {
880 return "TOP {$limit} " . $sql;
882 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
883 'SELECT$1 TOP ' . $limit, $sql, 1 );
886 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
887 $select = $orderby = [];
888 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
889 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
890 $overOrder = $postOrder = '';
891 $first = $offset +
1;
892 $last = $offset +
$limit;
893 $sub1 = 'sub_' . $this->mSubqueryId
;
894 $sub2 = 'sub_' . ( $this->mSubqueryId +
1 );
895 $this->mSubqueryId +
= 2;
898 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
902 $overOrder = 'ORDER BY (SELECT 1)';
904 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
905 // don't need to strip it out if we're using a FOR XML clause
906 $sql = str_replace( $orderby[1], '', $sql );
908 $overOrder = $orderby[1];
909 $postOrder = ' ' . $overOrder;
911 $sql = "SELECT {$select[1]}
913 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
914 FROM ({$sql}) {$sub1}
916 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
923 * If there is a limit clause, parse it, strip it, and pass the remaining
924 * SQL through limitResult() with the appropriate parameters. Not the
925 * prettiest solution, but better than building a whole new parser. This
926 * exists becase there are still too many extensions that don't use dynamic
930 * @return array|mixed|string
932 public function LimitToTopN( $sql ) {
933 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
934 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
935 if ( preg_match( $pattern, $sql, $matches ) ) {
936 $row_count = $matches[4];
937 $offset = $matches[3] ?
: $matches[6] ?
: false;
939 // strip the matching LIMIT clause out
940 $sql = str_replace( $matches[0], '', $sql );
942 return $this->limitResult( $sql, $row_count, $offset );
949 * @return string Wikitext of a link to the server software's web site
951 public function getSoftwareLink() {
952 return "[{{int:version-db-mssql-url}} MS SQL Server]";
956 * @return string Version information from the database
958 public function getServerVersion() {
959 $server_info = sqlsrv_server_info( $this->mConn
);
961 if ( isset( $server_info['SQLServerVersion'] ) ) {
962 $version = $server_info['SQLServerVersion'];
969 * @param string $table
970 * @param string $fname
973 public function tableExists( $table, $fname = __METHOD__
) {
974 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
976 if ( $db !== false ) {
978 wfDebug( "Attempting to call tableExists on a remote table" );
982 if ( $schema === false ) {
983 global $wgDBmwschema;
984 $schema = $wgDBmwschema;
987 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
988 WHERE TABLE_TYPE = 'BASE TABLE'
989 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
991 if ( $res->numRows() ) {
999 * Query whether a given column exists in the mediawiki schema
1000 * @param string $table
1001 * @param string $field
1002 * @param string $fname
1005 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1006 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1008 if ( $db !== false ) {
1010 wfDebug( "Attempting to call fieldExists on a remote table" );
1014 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1015 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1017 if ( $res->numRows() ) {
1024 public function fieldInfo( $table, $field ) {
1025 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1027 if ( $db !== false ) {
1029 wfDebug( "Attempting to call fieldInfo on a remote table" );
1033 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1034 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1036 $meta = $res->fetchRow();
1038 return new MssqlField( $meta );
1045 * Begin a transaction, committing any previously open transaction
1046 * @param string $fname
1048 protected function doBegin( $fname = __METHOD__
) {
1049 sqlsrv_begin_transaction( $this->mConn
);
1050 $this->mTrxLevel
= 1;
1055 * @param string $fname
1057 protected function doCommit( $fname = __METHOD__
) {
1058 sqlsrv_commit( $this->mConn
);
1059 $this->mTrxLevel
= 0;
1063 * Rollback a transaction.
1064 * No-op on non-transactional databases.
1065 * @param string $fname
1067 protected function doRollback( $fname = __METHOD__
) {
1068 sqlsrv_rollback( $this->mConn
);
1069 $this->mTrxLevel
= 0;
1073 * Escapes a identifier for use inm SQL.
1074 * Throws an exception if it is invalid.
1075 * Reference: http://msdn.microsoft.com/en-us/library/aa224033%28v=SQL.80%29.aspx
1076 * @param string $identifier
1077 * @throws MWException
1080 private function escapeIdentifier( $identifier ) {
1081 if ( strlen( $identifier ) == 0 ) {
1082 throw new InvalidArgumentException( "An identifier must not be empty" );
1084 if ( strlen( $identifier ) > 128 ) {
1085 throw new InvalidArgumentException( "The identifier '$identifier' is too long (max. 128)" );
1087 if ( ( strpos( $identifier, '[' ) !== false )
1088 ||
( strpos( $identifier, ']' ) !== false )
1090 // It may be allowed if you quoted with double quotation marks, but
1091 // that would break if QUOTED_IDENTIFIER is OFF
1092 throw new InvalidArgumentException( "Square brackets are not allowed in '$identifier'" );
1095 return "[$identifier]";
1102 public function strencode( $s ) {
1103 // Should not be called by us
1105 return str_replace( "'", "''", $s );
1109 * @param string|Blob $s
1112 public function addQuotes( $s ) {
1113 if ( $s instanceof MssqlBlob
) {
1115 } elseif ( $s instanceof Blob
) {
1116 // this shouldn't really ever be called, but it's here if needed
1117 // (and will quite possibly make the SQL error out)
1118 $blob = new MssqlBlob( $s->fetch() );
1119 return $blob->fetch();
1121 if ( is_bool( $s ) ) {
1124 return parent
::addQuotes( $s );
1132 public function addIdentifierQuotes( $s ) {
1133 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1134 return '[' . $s . ']';
1138 * @param string $name
1141 public function isQuotedIdentifier( $name ) {
1142 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1146 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1151 protected function escapeLikeInternal( $s ) {
1152 return addcslashes( $s, '\%_[]^' );
1156 * MS SQL requires specifying the escape character used in a LIKE query
1157 * or using Square brackets to surround characters that are to be escaped
1158 * http://msdn.microsoft.com/en-us/library/ms179859.aspx
1159 * Here we take the Specify-Escape-Character approach since it's less
1160 * invasive, renders a query that is closer to other DB's and better at
1161 * handling square bracket escaping
1163 * @return string Fully built LIKE statement
1165 public function buildLike() {
1166 $params = func_get_args();
1167 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1168 $params = $params[0];
1171 return parent
::buildLike( $params ) . " ESCAPE '\' ";
1178 public function selectDB( $db ) {
1180 $this->mDBname
= $db;
1181 $this->query( "USE $db" );
1183 } catch ( Exception
$e ) {
1189 * @param array $options An associative array of options to be turned into
1190 * an SQL query, valid keys are listed in the function.
1193 public function makeSelectOptions( $options ) {
1198 foreach ( $options as $key => $option ) {
1199 if ( is_numeric( $key ) ) {
1200 $noKeyOptions[$option] = true;
1204 $tailOpts .= $this->makeGroupByWithHaving( $options );
1206 $tailOpts .= $this->makeOrderBy( $options );
1208 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1209 $startOpts .= 'DISTINCT';
1212 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1213 // used in group concat field emulation
1214 $tailOpts .= " FOR XML PATH('')";
1217 // we want this to be compatible with the output of parent::makeSelectOptions()
1218 return [ $startOpts, '', $tailOpts, '', '' ];
1222 * Get the type of the DBMS, as it appears in $wgDBtype.
1225 public function getType() {
1230 * @param array $stringList
1233 public function buildConcat( $stringList ) {
1234 return implode( ' + ', $stringList );
1238 * Build a GROUP_CONCAT or equivalent statement for a query.
1239 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1241 * This is useful for combining a field for several rows into a single string.
1242 * NULL values will not appear in the output, duplicated values will appear,
1243 * and the resulting delimiter-separated values have no defined sort order.
1244 * Code using the results may need to use the PHP unique() or sort() methods.
1246 * @param string $delim Glue to bind the results together
1247 * @param string|array $table Table name
1248 * @param string $field Field name
1249 * @param string|array $conds Conditions
1250 * @param string|array $join_conds Join conditions
1251 * @return string SQL text
1254 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1257 $gcsq = 'gcsq_' . $this->mSubqueryId
;
1258 $this->mSubqueryId++
;
1260 $delimLen = strlen( $delim );
1261 $fld = "{$field} + {$this->addQuotes( $delim )}";
1262 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1263 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1264 . ") {$gcsq} ({$field}))";
1272 public function getSearchEngine() {
1273 return "SearchMssql";
1277 * Returns an associative array for fields that are of type varbinary, binary, or image
1278 * $table can be either a raw table name or passed through tableName() first
1279 * @param string $table
1282 private function getBinaryColumns( $table ) {
1283 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1284 $tableRaw = array_pop( $tableRawArr );
1286 if ( $this->mBinaryColumnCache
=== null ) {
1287 $this->populateColumnCaches();
1290 return isset( $this->mBinaryColumnCache
[$tableRaw] )
1291 ?
$this->mBinaryColumnCache
[$tableRaw]
1296 * @param string $table
1299 private function getBitColumns( $table ) {
1300 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1301 $tableRaw = array_pop( $tableRawArr );
1303 if ( $this->mBitColumnCache
=== null ) {
1304 $this->populateColumnCaches();
1307 return isset( $this->mBitColumnCache
[$tableRaw] )
1308 ?
$this->mBitColumnCache
[$tableRaw]
1312 private function populateColumnCaches() {
1313 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1315 'TABLE_CATALOG' => $this->mDBname
,
1316 'TABLE_SCHEMA' => $this->mSchema
,
1317 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1320 $this->mBinaryColumnCache
= [];
1321 $this->mBitColumnCache
= [];
1322 foreach ( $res as $row ) {
1323 if ( $row->DATA_TYPE
== 'bit' ) {
1324 $this->mBitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1326 $this->mBinaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1332 * @param string $name
1333 * @param string $format
1336 function tableName( $name, $format = 'quoted' ) {
1337 # Replace reserved words with better ones
1340 return $this->realTableName( 'mwuser', $format );
1342 return $this->realTableName( $name, $format );
1347 * call this instead of tableName() in the updater when renaming tables
1348 * @param string $name
1349 * @param string $format One of quoted, raw, or split
1352 function realTableName( $name, $format = 'quoted' ) {
1353 $table = parent
::tableName( $name, $format );
1354 if ( $format == 'split' ) {
1355 // Used internally, we want the schema split off from the table name and returned
1356 // as a list with 3 elements (database, schema, table)
1357 $table = explode( '.', $table );
1358 while ( count( $table ) < 3 ) {
1359 array_unshift( $table, false );
1367 * @param string $tableName
1368 * @param string $fName
1369 * @return bool|ResultWrapper
1372 public function dropTable( $tableName, $fName = __METHOD__
) {
1373 if ( !$this->tableExists( $tableName, $fName ) ) {
1377 // parent function incorrectly appends CASCADE, which we don't want
1378 $sql = "DROP TABLE " . $this->tableName( $tableName );
1380 return $this->query( $sql, $fName );
1384 * Called in the installer and updater.
1385 * Probably doesn't need to be called anywhere else in the codebase.
1386 * @param bool|null $value
1389 public function prepareStatements( $value = null ) {
1390 return wfSetVar( $this->mPrepareStatements
, $value );
1394 * Called in the installer and updater.
1395 * Probably doesn't need to be called anywhere else in the codebase.
1396 * @param bool|null $value
1399 public function scrollableCursor( $value = null ) {
1400 return wfSetVar( $this->mScrollableCursor
, $value );
1404 * Called in the installer and updater.
1405 * Probably doesn't need to be called anywhere else in the codebase.
1406 * @param array|null $value
1407 * @return array|null
1409 public function ignoreErrors( array $value = null ) {
1410 return wfSetVar( $this->mIgnoreErrors
, $value );
1412 } // end DatabaseMssql class
1419 class MssqlField
implements Field
{
1420 private $name, $tableName, $default, $max_length, $nullable, $type;
1422 function __construct( $info ) {
1423 $this->name
= $info['COLUMN_NAME'];
1424 $this->tableName
= $info['TABLE_NAME'];
1425 $this->default = $info['COLUMN_DEFAULT'];
1426 $this->max_length
= $info['CHARACTER_MAXIMUM_LENGTH'];
1427 $this->nullable
= !( strtolower( $info['IS_NULLABLE'] ) == 'no' );
1428 $this->type
= $info['DATA_TYPE'];
1435 function tableName() {
1436 return $this->tableName
;
1439 function defaultValue() {
1440 return $this->default;
1443 function maxLength() {
1444 return $this->max_length
;
1447 function isNullable() {
1448 return $this->nullable
;
1456 class MssqlBlob
extends Blob
{
1457 public function __construct( $data ) {
1458 if ( $data instanceof MssqlBlob
) {
1460 } elseif ( $data instanceof Blob
) {
1461 $this->mData
= $data->fetch();
1462 } elseif ( is_array( $data ) && is_object( $data ) ) {
1463 $this->mData
= serialize( $data );
1465 $this->mData
= $data;
1470 * Returns an unquoted hex representation of a binary string
1471 * for insertion into varbinary-type fields
1474 public function fetch() {
1475 if ( $this->mData
=== null ) {
1480 $dataLength = strlen( $this->mData
);
1481 for ( $i = 0; $i < $dataLength; $i++
) {
1482 $ret .= bin2hex( pack( 'C', ord( $this->mData
[$i] ) ) );
1489 class MssqlResultWrapper
extends ResultWrapper
{
1490 private $mSeekTo = null;
1493 * @return stdClass|bool
1495 public function fetchObject() {
1496 $res = $this->result
;
1498 if ( $this->mSeekTo
!== null ) {
1499 $result = sqlsrv_fetch_object( $res, 'stdClass', [],
1500 SQLSRV_SCROLL_ABSOLUTE
, $this->mSeekTo
);
1501 $this->mSeekTo
= null;
1503 $result = sqlsrv_fetch_object( $res );
1506 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1507 if ( $result === null ) {
1515 * @return array|bool
1517 public function fetchRow() {
1518 $res = $this->result
;
1520 if ( $this->mSeekTo
!== null ) {
1521 $result = sqlsrv_fetch_array( $res, SQLSRV_FETCH_BOTH
,
1522 SQLSRV_SCROLL_ABSOLUTE
, $this->mSeekTo
);
1523 $this->mSeekTo
= null;
1525 $result = sqlsrv_fetch_array( $res );
1528 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1529 if ( $result === null ) {
1540 public function seek( $row ) {
1541 $res = $this->result
;
1544 $numRows = $this->db
->numRows( $res );
1545 $row = intval( $row );
1547 if ( $numRows === 0 ) {
1549 } elseif ( $row < 0 ||
$row > $numRows - 1 ) {
1553 // Unlike MySQL, the seek actually happens on the next access
1554 $this->mSeekTo
= $row;