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
{
33 protected $mUseWindowsAuth = false;
35 protected $mInsertId = null;
36 protected $mLastResult = null;
37 protected $mAffectedRows = null;
38 protected $mSubqueryId = 0;
39 protected $mScrollableCursor = true;
40 protected $mPrepareStatements = true;
41 protected $mBinaryColumnCache = null;
42 protected $mBitColumnCache = null;
43 protected $mIgnoreDupKeyErrors = false;
44 protected $mIgnoreErrors = [];
46 public function implicitGroupby() {
50 public function implicitOrderby() {
54 public function unionSupportsOrderAndLimit() {
58 public function __construct( array $params ) {
59 $this->mPort
= $params['port'];
60 $this->mUseWindowsAuth
= $params['UseWindowsAuth'];
62 parent
::__construct( $params );
66 * Usually aborts on failure
67 * @param string $server
69 * @param string $password
70 * @param string $dbName
71 * @throws DBConnectionError
72 * @return bool|resource|null
74 public function open( $server, $user, $password, $dbName ) {
75 # Test for driver support, to avoid suppressed fatal error
76 if ( !function_exists( 'sqlsrv_connect' ) ) {
77 throw new DBConnectionError(
79 "Microsoft SQL Server Native (sqlsrv) functions missing.
80 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
84 # e.g. the class is being loaded
85 if ( !strlen( $user ) ) {
90 $this->mServer
= $server;
92 $this->mPassword
= $password;
93 $this->mDBname
= $dbName;
98 $connectionInfo['Database'] = $dbName;
101 // Decide which auth scenerio to use
102 // if we are using Windows auth, then don't add credentials to $connectionInfo
103 if ( !$this->mUseWindowsAuth
) {
104 $connectionInfo['UID'] = $user;
105 $connectionInfo['PWD'] = $password;
108 MediaWiki\
suppressWarnings();
109 $this->mConn
= sqlsrv_connect( $server, $connectionInfo );
110 MediaWiki\restoreWarnings
();
112 if ( $this->mConn
=== false ) {
113 throw new DBConnectionError( $this, $this->lastError() );
116 $this->mOpened
= true;
122 * Closes a database connection, if it is open
123 * Returns success, true if already closed
126 protected function closeConnection() {
127 return sqlsrv_close( $this->mConn
);
131 * @param bool|MssqlResultWrapper|resource $result
132 * @return bool|MssqlResultWrapper
134 protected function resultObject( $result ) {
137 } elseif ( $result instanceof MssqlResultWrapper
) {
139 } elseif ( $result === true ) {
140 // Successful write query
143 return new MssqlResultWrapper( $this, $result );
149 * @return bool|MssqlResultWrapper|resource
150 * @throws DBUnexpectedError
152 protected function doQuery( $sql ) {
153 // several extensions seem to think that all databases support limits
154 // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
155 // so to catch any of those extensions we'll do a quick check for a
156 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
157 // the LIMIT clause and passes the result to $this->limitResult();
158 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
159 // massage LIMIT -> TopN
160 $sql = $this->LimitToTopN( $sql );
163 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
164 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
165 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
166 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
171 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
172 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
173 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
174 // strings make php throw a fatal error "Severe error translating Unicode"
175 if ( $this->mScrollableCursor
) {
176 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
181 if ( $this->mPrepareStatements
) {
182 // we do prepare + execute so we can get its field metadata for later usage if desired
183 $stmt = sqlsrv_prepare( $this->mConn
, $sql, [], $scrollArr );
184 $success = sqlsrv_execute( $stmt );
186 $stmt = sqlsrv_query( $this->mConn
, $sql, [], $scrollArr );
187 $success = (bool)$stmt;
190 // Make a copy to ensure what we add below does not get reflected in future queries
191 $ignoreErrors = $this->mIgnoreErrors
;
193 if ( $this->mIgnoreDupKeyErrors
) {
194 // ignore duplicate key errors
195 // this emulates INSERT IGNORE in MySQL
196 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
197 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
198 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
201 if ( $success === false ) {
202 $errors = sqlsrv_errors();
205 foreach ( $errors as $err ) {
206 if ( !in_array( $err['code'], $ignoreErrors ) ) {
212 if ( $success === false ) {
216 // remember number of rows affected
217 $this->mAffectedRows
= sqlsrv_rows_affected( $stmt );
222 public function freeResult( $res ) {
223 if ( $res instanceof ResultWrapper
) {
227 sqlsrv_free_stmt( $res );
231 * @param MssqlResultWrapper $res
234 public function fetchObject( $res ) {
235 // $res is expected to be an instance of MssqlResultWrapper here
236 return $res->fetchObject();
240 * @param MssqlResultWrapper $res
243 public function fetchRow( $res ) {
244 return $res->fetchRow();
251 public function numRows( $res ) {
252 if ( $res instanceof ResultWrapper
) {
256 $ret = sqlsrv_num_rows( $res );
258 if ( $ret === false ) {
259 // we cannot get an amount of rows from this cursor type
260 // has_rows returns bool true/false if the result has rows
261 $ret = (int)sqlsrv_has_rows( $res );
271 public function numFields( $res ) {
272 if ( $res instanceof ResultWrapper
) {
276 return sqlsrv_num_fields( $res );
284 public function fieldName( $res, $n ) {
285 if ( $res instanceof ResultWrapper
) {
289 return sqlsrv_field_metadata( $res )[$n]['Name'];
293 * This must be called after nextSequenceVal
296 public function insertId() {
297 return $this->mInsertId
;
301 * @param MssqlResultWrapper $res
305 public function dataSeek( $res, $row ) {
306 return $res->seek( $row );
312 public function lastError() {
314 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
315 if ( $retErrors != null ) {
316 foreach ( $retErrors as $arrError ) {
317 $strRet .= $this->formatError( $arrError ) . "\n";
320 $strRet = "No errors found";
330 private function formatError( $err ) {
331 return '[SQLSTATE ' .
332 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
338 public function lastErrno() {
339 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
340 if ( $err !== null && isset( $err[0] ) ) {
341 return $err[0]['code'];
350 public function affectedRows() {
351 return $this->mAffectedRows
;
357 * @param mixed $table Array or string, table name(s) (prefix auto-added)
358 * @param mixed $vars Array or string, field name(s) to be retrieved
359 * @param mixed $conds Array or string, condition(s) for WHERE
360 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
361 * @param array $options Associative array of options (e.g.
362 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
363 * code for list of supported stuff
364 * @param array $join_conds Associative array of table join conditions
365 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
366 * @return mixed Database result resource (feed to Database::fetchObject
367 * or whatever), or false on failure
368 * @throws DBQueryError
369 * @throws DBUnexpectedError
372 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
373 $options = [], $join_conds = []
375 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
376 if ( isset( $options['EXPLAIN'] ) ) {
378 $this->mScrollableCursor
= false;
379 $this->mPrepareStatements
= false;
380 $this->query( "SET SHOWPLAN_ALL ON" );
381 $ret = $this->query( $sql, $fname );
382 $this->query( "SET SHOWPLAN_ALL OFF" );
383 } catch ( DBQueryError
$dqe ) {
384 if ( isset( $options['FOR COUNT'] ) ) {
385 // likely don't have privs for SHOWPLAN, so run a select count instead
386 $this->query( "SET SHOWPLAN_ALL OFF" );
387 unset( $options['EXPLAIN'] );
388 $ret = $this->select(
390 'COUNT(*) AS EstimateRows',
397 // someone actually wanted the query plan instead of an est row count
398 // let them know of the error
399 $this->mScrollableCursor
= true;
400 $this->mPrepareStatements
= true;
404 $this->mScrollableCursor
= true;
405 $this->mPrepareStatements
= true;
408 return $this->query( $sql, $fname );
414 * @param mixed $table Array or string, table name(s) (prefix auto-added)
415 * @param mixed $vars Array or string, field name(s) to be retrieved
416 * @param mixed $conds Array or string, condition(s) for WHERE
417 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
418 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
419 * see Database::makeSelectOptions code for list of supported stuff
420 * @param array $join_conds Associative array of table join conditions (optional)
421 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
422 * @return string The SQL text
424 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
425 $options = [], $join_conds = []
427 if ( isset( $options['EXPLAIN'] ) ) {
428 unset( $options['EXPLAIN'] );
431 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
433 // try to rewrite aggregations of bit columns (currently MAX and MIN)
434 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
436 if ( is_array( $table ) ) {
437 foreach ( $table as $t ) {
438 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
441 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
444 foreach ( $bitColumns as $col => $info ) {
446 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
447 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
449 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
456 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
459 $this->mScrollableCursor
= false;
461 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
462 } catch ( Exception
$e ) {
463 $this->mScrollableCursor
= true;
466 $this->mScrollableCursor
= true;
469 public function delete( $table, $conds, $fname = __METHOD__
) {
470 $this->mScrollableCursor
= false;
472 parent
::delete( $table, $conds, $fname );
473 } catch ( Exception
$e ) {
474 $this->mScrollableCursor
= true;
477 $this->mScrollableCursor
= true;
481 * Estimate rows in dataset
482 * Returns estimated count, based on SHOWPLAN_ALL output
483 * This is not necessarily an accurate estimate, so use sparingly
484 * Returns -1 if count cannot be found
485 * Takes same arguments as Database::select()
486 * @param string $table
487 * @param string $vars
488 * @param string $conds
489 * @param string $fname
490 * @param array $options
493 public function estimateRowCount( $table, $vars = '*', $conds = '',
494 $fname = __METHOD__
, $options = []
496 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
497 $options['EXPLAIN'] = true;
498 $options['FOR COUNT'] = true;
499 $res = $this->select( $table, $vars, $conds, $fname, $options );
503 $row = $this->fetchRow( $res );
505 if ( isset( $row['EstimateRows'] ) ) {
506 $rows = (int)$row['EstimateRows'];
514 * Returns information about an index
515 * If errors are explicitly ignored, returns NULL on failure
516 * @param string $table
517 * @param string $index
518 * @param string $fname
519 * @return array|bool|null
521 public function indexInfo( $table, $index, $fname = __METHOD__
) {
522 # This does not return the same info as MYSQL would, but that's OK
523 # because MediaWiki never uses the returned value except to check for
524 # the existence of indexes.
525 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
526 $res = $this->query( $sql, $fname );
533 foreach ( $res as $row ) {
534 if ( $row->index_name
== $index ) {
535 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
536 $cols = explode( ", ", $row->index_keys
);
537 foreach ( $cols as $col ) {
538 $row->Column_name
= trim( $col );
539 $result[] = clone $row;
541 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
542 $row->Non_unique
= 0;
543 $cols = explode( ", ", $row->index_keys
);
544 foreach ( $cols as $col ) {
545 $row->Column_name
= trim( $col );
546 $result[] = clone $row;
551 return empty( $result ) ?
false : $result;
555 * INSERT wrapper, inserts an array into a table
557 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
560 * Usually aborts on failure
561 * If errors are explicitly ignored, returns success
562 * @param string $table
563 * @param array $arrToInsert
564 * @param string $fname
565 * @param array $options
569 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
570 # No rows to insert, easy just return now
571 if ( !count( $arrToInsert ) ) {
575 if ( !is_array( $options ) ) {
576 $options = [ $options ];
579 $table = $this->tableName( $table );
581 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
582 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
585 // We know the table we're inserting into, get its identity column
587 // strip matching square brackets and the db/schema from table name
588 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
589 $tableRaw = array_pop( $tableRawArr );
590 $res = $this->doQuery(
591 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
592 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
594 if ( $res && sqlsrv_has_rows( $res ) ) {
595 // There is an identity for this table.
596 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
597 $identity = array_pop( $identityArr );
599 sqlsrv_free_stmt( $res );
601 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
602 $binaryColumns = $this->getBinaryColumns( $table );
604 // INSERT IGNORE is not supported by SQL Server
605 // remove IGNORE from options list and set ignore flag to true
606 if ( in_array( 'IGNORE', $options ) ) {
607 $options = array_diff( $options, [ 'IGNORE' ] );
608 $this->mIgnoreDupKeyErrors
= true;
612 foreach ( $arrToInsert as $a ) {
613 // start out with empty identity column, this is so we can return
614 // it as a result of the INSERT logic
617 $identityClause = '';
619 // if we have an identity column
622 foreach ( $a as $k => $v ) {
623 if ( $k == $identity ) {
624 if ( !is_null( $v ) ) {
625 // there is a value being passed to us,
626 // we need to turn on and off inserted identity
627 $sqlPre = "SET IDENTITY_INSERT $table ON;";
628 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
630 // we can't insert NULL into an identity column,
631 // so remove the column from the insert.
637 // we want to output an identity column as result
638 $identityClause = "OUTPUT INSERTED.$identity ";
641 $keys = array_keys( $a );
643 // Build the actual query
644 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
645 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
648 foreach ( $a as $key => $value ) {
649 if ( isset( $binaryColumns[$key] ) ) {
650 $value = new MssqlBlob( $value );
657 if ( is_null( $value ) ) {
659 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
660 if ( is_object( $value ) && $value instanceof Blob
) {
661 $sql .= $this->addQuotes( $value );
663 $sql .= $this->addQuotes( serialize( $value ) );
666 $sql .= $this->addQuotes( $value );
669 $sql .= ')' . $sqlPost;
672 $this->mScrollableCursor
= false;
674 $ret = $this->query( $sql );
675 } catch ( Exception
$e ) {
676 $this->mScrollableCursor
= true;
677 $this->mIgnoreDupKeyErrors
= false;
680 $this->mScrollableCursor
= true;
682 if ( $ret instanceof ResultWrapper
&& !is_null( $identity ) ) {
683 // Then we want to get the identity column value we were assigned and save it off
684 $row = $ret->fetchObject();
685 if ( is_object( $row ) ) {
686 $this->mInsertId
= $row->$identity;
687 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
688 // used if we got an identity back, we know for sure a row was affected, so
690 if ( $this->mAffectedRows
== -1 ) {
691 $this->mAffectedRows
= 1;
697 $this->mIgnoreDupKeyErrors
= false;
703 * INSERT SELECT wrapper
704 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
705 * Source items may be literals rather than field names, but strings should
706 * be quoted with Database::addQuotes().
707 * @param string $destTable
708 * @param array|string $srcTable May be an array of tables.
709 * @param array $varMap
710 * @param array $conds May be "*" to copy the whole table.
711 * @param string $fname
712 * @param array $insertOptions
713 * @param array $selectOptions
714 * @return null|ResultWrapper
717 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
718 $insertOptions = [], $selectOptions = []
720 $this->mScrollableCursor
= false;
722 $ret = parent
::nativeInsertSelect(
731 } catch ( Exception
$e ) {
732 $this->mScrollableCursor
= true;
735 $this->mScrollableCursor
= true;
741 * UPDATE wrapper. Takes a condition array and a SET array.
743 * @param string $table Name of the table to UPDATE. This will be passed through
744 * Database::tableName().
746 * @param array $values An array of values to SET. For each array element,
747 * the key gives the field name, and the value gives the data
748 * to set that field to. The data will be quoted by
749 * Database::addQuotes().
751 * @param array $conds An array of conditions (WHERE). See
752 * Database::select() for the details of the format of
753 * condition arrays. Use '*' to update all rows.
755 * @param string $fname The function name of the caller (from __METHOD__),
756 * for logging and profiling.
758 * @param array $options An array of UPDATE options, can be:
759 * - IGNORE: Ignore unique key conflicts
760 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
762 * @throws DBUnexpectedError
765 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
766 $table = $this->tableName( $table );
767 $binaryColumns = $this->getBinaryColumns( $table );
769 $opts = $this->makeUpdateOptions( $options );
770 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
772 if ( $conds !== [] && $conds !== '*' ) {
773 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
776 $this->mScrollableCursor
= false;
778 $this->query( $sql );
779 } catch ( Exception
$e ) {
780 $this->mScrollableCursor
= true;
783 $this->mScrollableCursor
= true;
788 * Makes an encoded list of strings from an array
789 * @param array $a Containing the data
790 * @param int $mode Constant
791 * - LIST_COMMA: comma separated, no field names
792 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
793 * the documentation for $conds in Database::select().
794 * - LIST_OR: ORed WHERE clause (without the WHERE)
795 * - LIST_SET: comma separated with field names, like a SET clause
796 * - LIST_NAMES: comma separated field names
797 * @param array $binaryColumns Contains a list of column names that are binary types
798 * This is a custom parameter only present for MS SQL.
800 * @throws DBUnexpectedError
803 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
804 if ( !is_array( $a ) ) {
805 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
808 if ( $mode != LIST_NAMES
) {
809 // In MS SQL, values need to be specially encoded when they are
810 // inserted into binary fields. Perform this necessary encoding
811 // for the specified set of columns.
812 foreach ( array_keys( $a ) as $field ) {
813 if ( !isset( $binaryColumns[$field] ) ) {
817 if ( is_array( $a[$field] ) ) {
818 foreach ( $a[$field] as &$v ) {
819 $v = new MssqlBlob( $v );
823 $a[$field] = new MssqlBlob( $a[$field] );
828 return parent
::makeList( $a, $mode );
832 * @param string $table
833 * @param string $field
834 * @return int Returns the size of a text field, or -1 for "unlimited"
836 public function textFieldSize( $table, $field ) {
837 $table = $this->tableName( $table );
838 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
839 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
840 $res = $this->query( $sql );
841 $row = $this->fetchRow( $res );
843 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
844 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
851 * Construct a LIMIT query with optional offset
852 * This is used for query pages
854 * @param string $sql SQL query we will append the limit too
855 * @param int $limit The SQL limit
856 * @param bool|int $offset The SQL offset (default false)
857 * @return array|string
858 * @throws DBUnexpectedError
860 public function limitResult( $sql, $limit, $offset = false ) {
861 if ( $offset === false ||
$offset == 0 ) {
862 if ( strpos( $sql, "SELECT" ) === false ) {
863 return "TOP {$limit} " . $sql;
865 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
866 'SELECT$1 TOP ' . $limit, $sql, 1 );
869 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
870 $select = $orderby = [];
871 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
872 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
874 $first = $offset +
1;
875 $last = $offset +
$limit;
876 $sub1 = 'sub_' . $this->mSubqueryId
;
877 $sub2 = 'sub_' . ( $this->mSubqueryId +
1 );
878 $this->mSubqueryId +
= 2;
881 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
885 $overOrder = 'ORDER BY (SELECT 1)';
887 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
888 // don't need to strip it out if we're using a FOR XML clause
889 $sql = str_replace( $orderby[1], '', $sql );
891 $overOrder = $orderby[1];
892 $postOrder = ' ' . $overOrder;
894 $sql = "SELECT {$select[1]}
896 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
897 FROM ({$sql}) {$sub1}
899 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
906 * If there is a limit clause, parse it, strip it, and pass the remaining
907 * SQL through limitResult() with the appropriate parameters. Not the
908 * prettiest solution, but better than building a whole new parser. This
909 * exists becase there are still too many extensions that don't use dynamic
913 * @return array|mixed|string
915 public function LimitToTopN( $sql ) {
916 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
917 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
918 if ( preg_match( $pattern, $sql, $matches ) ) {
919 $row_count = $matches[4];
920 $offset = $matches[3] ?
: $matches[6] ?
: false;
922 // strip the matching LIMIT clause out
923 $sql = str_replace( $matches[0], '', $sql );
925 return $this->limitResult( $sql, $row_count, $offset );
932 * @return string Wikitext of a link to the server software's web site
934 public function getSoftwareLink() {
935 return "[{{int:version-db-mssql-url}} MS SQL Server]";
939 * @return string Version information from the database
941 public function getServerVersion() {
942 $server_info = sqlsrv_server_info( $this->mConn
);
944 if ( isset( $server_info['SQLServerVersion'] ) ) {
945 $version = $server_info['SQLServerVersion'];
952 * @param string $table
953 * @param string $fname
956 public function tableExists( $table, $fname = __METHOD__
) {
957 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
959 if ( $db !== false ) {
961 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
965 if ( $schema === false ) {
966 $schema = $this->mSchema
;
969 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
970 WHERE TABLE_TYPE = 'BASE TABLE'
971 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
973 if ( $res->numRows() ) {
981 * Query whether a given column exists in the mediawiki schema
982 * @param string $table
983 * @param string $field
984 * @param string $fname
987 public function fieldExists( $table, $field, $fname = __METHOD__
) {
988 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
990 if ( $db !== false ) {
992 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
996 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
997 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
999 if ( $res->numRows() ) {
1006 public function fieldInfo( $table, $field ) {
1007 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1009 if ( $db !== false ) {
1011 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1015 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1016 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1018 $meta = $res->fetchRow();
1020 return new MssqlField( $meta );
1027 * Begin a transaction, committing any previously open transaction
1028 * @param string $fname
1030 protected function doBegin( $fname = __METHOD__
) {
1031 sqlsrv_begin_transaction( $this->mConn
);
1032 $this->mTrxLevel
= 1;
1037 * @param string $fname
1039 protected function doCommit( $fname = __METHOD__
) {
1040 sqlsrv_commit( $this->mConn
);
1041 $this->mTrxLevel
= 0;
1045 * Rollback a transaction.
1046 * No-op on non-transactional databases.
1047 * @param string $fname
1049 protected function doRollback( $fname = __METHOD__
) {
1050 sqlsrv_rollback( $this->mConn
);
1051 $this->mTrxLevel
= 0;
1058 public function strencode( $s ) {
1059 // Should not be called by us
1061 return str_replace( "'", "''", $s );
1065 * @param string|int|null|bool|Blob $s
1066 * @return string|int
1068 public function addQuotes( $s ) {
1069 if ( $s instanceof MssqlBlob
) {
1071 } elseif ( $s instanceof Blob
) {
1072 // this shouldn't really ever be called, but it's here if needed
1073 // (and will quite possibly make the SQL error out)
1074 $blob = new MssqlBlob( $s->fetch() );
1075 return $blob->fetch();
1077 if ( is_bool( $s ) ) {
1080 return parent
::addQuotes( $s );
1088 public function addIdentifierQuotes( $s ) {
1089 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1090 return '[' . $s . ']';
1094 * @param string $name
1097 public function isQuotedIdentifier( $name ) {
1098 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1102 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1107 protected function escapeLikeInternal( $s ) {
1108 return addcslashes( $s, '\%_[]^' );
1112 * MS SQL requires specifying the escape character used in a LIKE query
1113 * or using Square brackets to surround characters that are to be escaped
1114 * https://msdn.microsoft.com/en-us/library/ms179859.aspx
1115 * Here we take the Specify-Escape-Character approach since it's less
1116 * invasive, renders a query that is closer to other DB's and better at
1117 * handling square bracket escaping
1119 * @return string Fully built LIKE statement
1121 public function buildLike() {
1122 $params = func_get_args();
1123 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1124 $params = $params[0];
1127 return parent
::buildLike( $params ) . " ESCAPE '\' ";
1134 public function selectDB( $db ) {
1136 $this->mDBname
= $db;
1137 $this->query( "USE $db" );
1139 } catch ( Exception
$e ) {
1145 * @param array $options An associative array of options to be turned into
1146 * an SQL query, valid keys are listed in the function.
1149 public function makeSelectOptions( $options ) {
1154 foreach ( $options as $key => $option ) {
1155 if ( is_numeric( $key ) ) {
1156 $noKeyOptions[$option] = true;
1160 $tailOpts .= $this->makeGroupByWithHaving( $options );
1162 $tailOpts .= $this->makeOrderBy( $options );
1164 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1165 $startOpts .= 'DISTINCT';
1168 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1169 // used in group concat field emulation
1170 $tailOpts .= " FOR XML PATH('')";
1173 // we want this to be compatible with the output of parent::makeSelectOptions()
1174 return [ $startOpts, '', $tailOpts, '', '' ];
1177 public function getType() {
1182 * @param array $stringList
1185 public function buildConcat( $stringList ) {
1186 return implode( ' + ', $stringList );
1190 * Build a GROUP_CONCAT or equivalent statement for a query.
1191 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1193 * This is useful for combining a field for several rows into a single string.
1194 * NULL values will not appear in the output, duplicated values will appear,
1195 * and the resulting delimiter-separated values have no defined sort order.
1196 * Code using the results may need to use the PHP unique() or sort() methods.
1198 * @param string $delim Glue to bind the results together
1199 * @param string|array $table Table name
1200 * @param string $field Field name
1201 * @param string|array $conds Conditions
1202 * @param string|array $join_conds Join conditions
1203 * @return string SQL text
1206 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1209 $gcsq = 'gcsq_' . $this->mSubqueryId
;
1210 $this->mSubqueryId++
;
1212 $delimLen = strlen( $delim );
1213 $fld = "{$field} + {$this->addQuotes( $delim )}";
1214 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1215 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1216 . ") {$gcsq} ({$field}))";
1222 * Returns an associative array for fields that are of type varbinary, binary, or image
1223 * $table can be either a raw table name or passed through tableName() first
1224 * @param string $table
1227 private function getBinaryColumns( $table ) {
1228 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1229 $tableRaw = array_pop( $tableRawArr );
1231 if ( $this->mBinaryColumnCache
=== null ) {
1232 $this->populateColumnCaches();
1235 return isset( $this->mBinaryColumnCache
[$tableRaw] )
1236 ?
$this->mBinaryColumnCache
[$tableRaw]
1241 * @param string $table
1244 private function getBitColumns( $table ) {
1245 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1246 $tableRaw = array_pop( $tableRawArr );
1248 if ( $this->mBitColumnCache
=== null ) {
1249 $this->populateColumnCaches();
1252 return isset( $this->mBitColumnCache
[$tableRaw] )
1253 ?
$this->mBitColumnCache
[$tableRaw]
1257 private function populateColumnCaches() {
1258 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1260 'TABLE_CATALOG' => $this->mDBname
,
1261 'TABLE_SCHEMA' => $this->mSchema
,
1262 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1265 $this->mBinaryColumnCache
= [];
1266 $this->mBitColumnCache
= [];
1267 foreach ( $res as $row ) {
1268 if ( $row->DATA_TYPE
== 'bit' ) {
1269 $this->mBitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1271 $this->mBinaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1277 * @param string $name
1278 * @param string $format
1281 function tableName( $name, $format = 'quoted' ) {
1282 # Replace reserved words with better ones
1285 return $this->realTableName( 'mwuser', $format );
1287 return $this->realTableName( $name, $format );
1292 * call this instead of tableName() in the updater when renaming tables
1293 * @param string $name
1294 * @param string $format One of quoted, raw, or split
1297 function realTableName( $name, $format = 'quoted' ) {
1298 $table = parent
::tableName( $name, $format );
1299 if ( $format == 'split' ) {
1300 // Used internally, we want the schema split off from the table name and returned
1301 // as a list with 3 elements (database, schema, table)
1302 $table = explode( '.', $table );
1303 while ( count( $table ) < 3 ) {
1304 array_unshift( $table, false );
1312 * @param string $tableName
1313 * @param string $fName
1314 * @return bool|ResultWrapper
1317 public function dropTable( $tableName, $fName = __METHOD__
) {
1318 if ( !$this->tableExists( $tableName, $fName ) ) {
1322 // parent function incorrectly appends CASCADE, which we don't want
1323 $sql = "DROP TABLE " . $this->tableName( $tableName );
1325 return $this->query( $sql, $fName );
1329 * Called in the installer and updater.
1330 * Probably doesn't need to be called anywhere else in the codebase.
1331 * @param bool|null $value
1334 public function prepareStatements( $value = null ) {
1335 $old = $this->mPrepareStatements
;
1336 if ( $value !== null ) {
1337 $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 $old = $this->mScrollableCursor
;
1351 if ( $value !== null ) {
1352 $this->mScrollableCursor
= $value;