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>
28 namespace Wikimedia\Rdbms
;
37 class DatabaseMssql
extends Database
{
39 protected $serverPort;
41 protected $useWindowsAuth = false;
43 protected $lastInsertId = null;
45 protected $lastAffectedRowCount = null;
47 protected $subqueryId = 0;
49 protected $scrollableCursor = true;
51 protected $prepareStatements = true;
52 /** @var stdClass[][]|null */
53 protected $binaryColumnCache = null;
54 /** @var stdClass[][]|null */
55 protected $bitColumnCache = null;
57 protected $ignoreDupKeyErrors = false;
59 protected $ignoreErrors = [];
61 public function implicitGroupby() {
65 public function implicitOrderby() {
69 public function unionSupportsOrderAndLimit() {
73 public function __construct( array $params ) {
74 $this->serverPort
= $params['port'];
75 $this->useWindowsAuth
= $params['UseWindowsAuth'];
77 parent
::__construct( $params );
80 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
81 # Test for driver support, to avoid suppressed fatal error
82 if ( !function_exists( 'sqlsrv_connect' ) ) {
83 throw new DBConnectionError(
85 "Microsoft SQL Server Native (sqlsrv) functions missing.
86 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
90 # e.g. the class is being loaded
91 if ( !strlen( $user ) ) {
96 $this->server
= $server;
98 $this->password
= $password;
100 $connectionInfo = [];
102 if ( $dbName != '' ) {
103 $connectionInfo['Database'] = $dbName;
106 // Decide which auth scenerio to use
107 // if we are using Windows auth, then don't add credentials to $connectionInfo
108 if ( !$this->useWindowsAuth
) {
109 $connectionInfo['UID'] = $user;
110 $connectionInfo['PWD'] = $password;
113 Wikimedia\
suppressWarnings();
114 $this->conn
= sqlsrv_connect( $server, $connectionInfo );
115 Wikimedia\restoreWarnings
();
117 if ( $this->conn
=== false ) {
118 throw new DBConnectionError( $this, $this->lastError() );
121 $this->opened
= true;
122 $this->currentDomain
= new DatabaseDomain(
123 ( $dbName != '' ) ?
$dbName : null,
128 return (bool)$this->conn
;
132 * Closes a database connection, if it is open
133 * Returns success, true if already closed
136 protected function closeConnection() {
137 return sqlsrv_close( $this->conn
);
141 * @param bool|MssqlResultWrapper|resource $result
142 * @return bool|MssqlResultWrapper
144 protected function resultObject( $result ) {
147 } elseif ( $result instanceof MssqlResultWrapper
) {
149 } elseif ( $result === true ) {
150 // Successful write query
153 return new MssqlResultWrapper( $this, $result );
159 * @return bool|MssqlResultWrapper|resource
161 protected function doQuery( $sql ) {
162 // several extensions seem to think that all databases support limits
163 // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
164 // so to catch any of those extensions we'll do a quick check for a
165 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
166 // the LIMIT clause and passes the result to $this->limitResult();
167 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
168 // massage LIMIT -> TopN
169 $sql = $this->LimitToTopN( $sql );
172 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
173 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
174 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
175 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
180 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
181 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
182 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
183 // strings make php throw a fatal error "Severe error translating Unicode"
184 if ( $this->scrollableCursor
) {
185 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
190 if ( $this->prepareStatements
) {
191 // we do prepare + execute so we can get its field metadata for later usage if desired
192 $stmt = sqlsrv_prepare( $this->conn
, $sql, [], $scrollArr );
193 $success = sqlsrv_execute( $stmt );
195 $stmt = sqlsrv_query( $this->conn
, $sql, [], $scrollArr );
196 $success = (bool)$stmt;
199 // Make a copy to ensure what we add below does not get reflected in future queries
200 $ignoreErrors = $this->ignoreErrors
;
202 if ( $this->ignoreDupKeyErrors
) {
203 // ignore duplicate key errors
204 // this emulates INSERT IGNORE in MySQL
205 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
206 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
207 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
210 if ( $success === false ) {
211 $errors = sqlsrv_errors();
214 foreach ( $errors as $err ) {
215 if ( !in_array( $err['code'], $ignoreErrors ) ) {
221 if ( $success === false ) {
225 // remember number of rows affected
226 $this->lastAffectedRowCount
= sqlsrv_rows_affected( $stmt );
231 public function freeResult( $res ) {
232 if ( $res instanceof ResultWrapper
) {
236 sqlsrv_free_stmt( $res );
240 * @param IResultWrapper $res
243 public function fetchObject( $res ) {
244 // $res is expected to be an instance of MssqlResultWrapper here
245 return $res->fetchObject();
249 * @param IResultWrapper $res
252 public function fetchRow( $res ) {
253 return $res->fetchRow();
260 public function numRows( $res ) {
261 if ( $res instanceof ResultWrapper
) {
265 $ret = sqlsrv_num_rows( $res );
267 if ( $ret === false ) {
268 // we cannot get an amount of rows from this cursor type
269 // has_rows returns bool true/false if the result has rows
270 $ret = (int)sqlsrv_has_rows( $res );
280 public function numFields( $res ) {
281 if ( $res instanceof ResultWrapper
) {
285 return sqlsrv_num_fields( $res );
293 public function fieldName( $res, $n ) {
294 if ( $res instanceof ResultWrapper
) {
298 return sqlsrv_field_metadata( $res )[$n]['Name'];
302 * This must be called after nextSequenceVal
305 public function insertId() {
306 return $this->lastInsertId
;
310 * @param MssqlResultWrapper $res
314 public function dataSeek( $res, $row ) {
315 return $res->seek( $row );
321 public function lastError() {
323 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
324 if ( $retErrors != null ) {
325 foreach ( $retErrors as $arrError ) {
326 $strRet .= $this->formatError( $arrError ) . "\n";
329 $strRet = "No errors found";
339 private function formatError( $err ) {
340 return '[SQLSTATE ' .
341 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
347 public function lastErrno() {
348 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
349 if ( $err !== null && isset( $err[0] ) ) {
350 return $err[0]['code'];
356 protected function wasKnownStatementRollbackError() {
357 $errors = sqlsrv_errors( SQLSRV_ERR_ALL
);
361 // The transaction vs statement rollback behavior depends on XACT_ABORT, so make sure
362 // that the "statement has been terminated" error (3621) is specifically present.
363 // https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql
364 $statementOnly = false;
365 $codeWhitelist = [ '2601', '2627', '547' ];
366 foreach ( $errors as $error ) {
367 if ( $error['code'] == '3621' ) {
368 $statementOnly = true;
369 } elseif ( !in_array( $error['code'], $codeWhitelist ) ) {
370 $statementOnly = false;
375 return $statementOnly;
381 protected function fetchAffectedRowCount() {
382 return $this->lastAffectedRowCount
;
388 * @param mixed $table Array or string, table name(s) (prefix auto-added)
389 * @param mixed $vars Array or string, field name(s) to be retrieved
390 * @param mixed $conds Array or string, condition(s) for WHERE
391 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
392 * @param array $options Associative array of options (e.g.
393 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
394 * code for list of supported stuff
395 * @param array $join_conds Associative array of table join conditions
396 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
397 * @return mixed Database result resource (feed to Database::fetchObject
398 * or whatever), or false on failure
399 * @throws DBQueryError
400 * @throws DBUnexpectedError
403 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
404 $options = [], $join_conds = []
406 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
407 if ( isset( $options['EXPLAIN'] ) ) {
409 $this->scrollableCursor
= false;
410 $this->prepareStatements
= false;
411 $this->query( "SET SHOWPLAN_ALL ON" );
412 $ret = $this->query( $sql, $fname );
413 $this->query( "SET SHOWPLAN_ALL OFF" );
414 } catch ( DBQueryError
$dqe ) {
415 if ( isset( $options['FOR COUNT'] ) ) {
416 // likely don't have privs for SHOWPLAN, so run a select count instead
417 $this->query( "SET SHOWPLAN_ALL OFF" );
418 unset( $options['EXPLAIN'] );
419 $ret = $this->select(
421 'COUNT(*) AS EstimateRows',
428 // someone actually wanted the query plan instead of an est row count
429 // let them know of the error
430 $this->scrollableCursor
= true;
431 $this->prepareStatements
= true;
435 $this->scrollableCursor
= true;
436 $this->prepareStatements
= true;
439 return $this->query( $sql, $fname );
445 * @param mixed $table Array or string, table name(s) (prefix auto-added)
446 * @param mixed $vars Array or string, field name(s) to be retrieved
447 * @param mixed $conds Array or string, condition(s) for WHERE
448 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
449 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
450 * see Database::makeSelectOptions code for list of supported stuff
451 * @param array $join_conds Associative array of table join conditions (optional)
452 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
453 * @return string The SQL text
455 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
456 $options = [], $join_conds = []
458 if ( isset( $options['EXPLAIN'] ) ) {
459 unset( $options['EXPLAIN'] );
462 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
464 // try to rewrite aggregations of bit columns (currently MAX and MIN)
465 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
467 if ( is_array( $table ) ) {
470 $t = array_pop( $tables );
471 if ( is_array( $t ) ) {
472 $tables = array_merge( $tables, $t );
474 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
478 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
481 foreach ( $bitColumns as $col => $info ) {
483 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
484 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
486 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
493 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
496 $this->scrollableCursor
= false;
498 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
499 } catch ( Exception
$e ) {
500 $this->scrollableCursor
= true;
503 $this->scrollableCursor
= true;
506 public function delete( $table, $conds, $fname = __METHOD__
) {
507 $this->scrollableCursor
= false;
509 parent
::delete( $table, $conds, $fname );
510 } catch ( Exception
$e ) {
511 $this->scrollableCursor
= true;
514 $this->scrollableCursor
= true;
520 * Estimate rows in dataset
521 * Returns estimated count, based on SHOWPLAN_ALL output
522 * This is not necessarily an accurate estimate, so use sparingly
523 * Returns -1 if count cannot be found
524 * Takes same arguments as Database::select()
525 * @param string $table
527 * @param string $conds
528 * @param string $fname
529 * @param array $options
530 * @param array $join_conds
533 public function estimateRowCount( $table, $var = '*', $conds = '',
534 $fname = __METHOD__
, $options = [], $join_conds = []
536 $conds = $this->normalizeConditions( $conds, $fname );
537 $column = $this->extractSingleFieldFromList( $var );
538 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
539 $conds[] = "$column IS NOT NULL";
542 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
543 $options['EXPLAIN'] = true;
544 $options['FOR COUNT'] = true;
545 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
549 $row = $this->fetchRow( $res );
551 if ( isset( $row['EstimateRows'] ) ) {
552 $rows = (int)$row['EstimateRows'];
560 * Returns information about an index
561 * If errors are explicitly ignored, returns NULL on failure
562 * @param string $table
563 * @param string $index
564 * @param string $fname
565 * @return array|bool|null
567 public function indexInfo( $table, $index, $fname = __METHOD__
) {
568 # This does not return the same info as MYSQL would, but that's OK
569 # because MediaWiki never uses the returned value except to check for
570 # the existence of indexes.
571 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
572 $res = $this->query( $sql, $fname );
579 foreach ( $res as $row ) {
580 if ( $row->index_name
== $index ) {
581 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
582 $cols = explode( ", ", $row->index_keys
);
583 foreach ( $cols as $col ) {
584 $row->Column_name
= trim( $col );
585 $result[] = clone $row;
587 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
588 $row->Non_unique
= 0;
589 $cols = explode( ", ", $row->index_keys
);
590 foreach ( $cols as $col ) {
591 $row->Column_name
= trim( $col );
592 $result[] = clone $row;
597 return $result ?
: false;
601 * INSERT wrapper, inserts an array into a table
603 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
606 * Usually aborts on failure
607 * If errors are explicitly ignored, returns success
608 * @param string $table
609 * @param array $arrToInsert
610 * @param string $fname
611 * @param array $options
615 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
616 # No rows to insert, easy just return now
617 if ( !count( $arrToInsert ) ) {
621 if ( !is_array( $options ) ) {
622 $options = [ $options ];
625 $table = $this->tableName( $table );
627 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
628 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
631 // We know the table we're inserting into, get its identity column
633 // strip matching square brackets and the db/schema from table name
634 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
635 $tableRaw = array_pop( $tableRawArr );
636 $res = $this->doQuery(
637 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
638 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
640 if ( $res && sqlsrv_has_rows( $res ) ) {
641 // There is an identity for this table.
642 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
643 $identity = array_pop( $identityArr );
645 sqlsrv_free_stmt( $res );
647 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
648 $binaryColumns = $this->getBinaryColumns( $table );
650 // INSERT IGNORE is not supported by SQL Server
651 // remove IGNORE from options list and set ignore flag to true
652 if ( in_array( 'IGNORE', $options ) ) {
653 $options = array_diff( $options, [ 'IGNORE' ] );
654 $this->ignoreDupKeyErrors
= true;
658 foreach ( $arrToInsert as $a ) {
659 // start out with empty identity column, this is so we can return
660 // it as a result of the INSERT logic
663 $identityClause = '';
665 // if we have an identity column
668 foreach ( $a as $k => $v ) {
669 if ( $k == $identity ) {
670 if ( !is_null( $v ) ) {
671 // there is a value being passed to us,
672 // we need to turn on and off inserted identity
673 $sqlPre = "SET IDENTITY_INSERT $table ON;";
674 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
676 // we can't insert NULL into an identity column,
677 // so remove the column from the insert.
683 // we want to output an identity column as result
684 $identityClause = "OUTPUT INSERTED.$identity ";
687 $keys = array_keys( $a );
689 // Build the actual query
690 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
691 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
694 foreach ( $a as $key => $value ) {
695 if ( isset( $binaryColumns[$key] ) ) {
696 $value = new MssqlBlob( $value );
703 if ( is_null( $value ) ) {
706 $sql .= $this->addQuotes( $value );
709 $sql .= ')' . $sqlPost;
712 $this->scrollableCursor
= false;
714 $ret = $this->query( $sql );
715 } catch ( Exception
$e ) {
716 $this->scrollableCursor
= true;
717 $this->ignoreDupKeyErrors
= false;
720 $this->scrollableCursor
= true;
722 if ( $ret instanceof ResultWrapper
&& !is_null( $identity ) ) {
723 // Then we want to get the identity column value we were assigned and save it off
724 $row = $ret->fetchObject();
725 if ( is_object( $row ) ) {
726 $this->lastInsertId
= $row->$identity;
727 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
728 // used if we got an identity back, we know for sure a row was affected, so
730 if ( $this->lastAffectedRowCount
== -1 ) {
731 $this->lastAffectedRowCount
= 1;
737 $this->ignoreDupKeyErrors
= false;
743 * INSERT SELECT wrapper
744 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
745 * Source items may be literals rather than field names, but strings should
746 * be quoted with Database::addQuotes().
747 * @param string $destTable
748 * @param array|string $srcTable May be an array of tables.
749 * @param array $varMap
750 * @param array $conds May be "*" to copy the whole table.
751 * @param string $fname
752 * @param array $insertOptions
753 * @param array $selectOptions
754 * @param array $selectJoinConds
757 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
758 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
760 $this->scrollableCursor
= false;
762 parent
::nativeInsertSelect(
772 } catch ( Exception
$e ) {
773 $this->scrollableCursor
= true;
776 $this->scrollableCursor
= true;
780 * UPDATE wrapper. Takes a condition array and a SET array.
782 * @param string $table Name of the table to UPDATE. This will be passed through
783 * Database::tableName().
785 * @param array $values An array of values to SET. For each array element,
786 * the key gives the field name, and the value gives the data
787 * to set that field to. The data will be quoted by
788 * Database::addQuotes().
790 * @param array $conds An array of conditions (WHERE). See
791 * Database::select() for the details of the format of
792 * condition arrays. Use '*' to update all rows.
794 * @param string $fname The function name of the caller (from __METHOD__),
795 * for logging and profiling.
797 * @param array $options An array of UPDATE options, can be:
798 * - IGNORE: Ignore unique key conflicts
799 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
801 * @throws DBUnexpectedError
804 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
805 $table = $this->tableName( $table );
806 $binaryColumns = $this->getBinaryColumns( $table );
808 $opts = $this->makeUpdateOptions( $options );
809 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
811 if ( $conds !== [] && $conds !== '*' ) {
812 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
815 $this->scrollableCursor
= false;
817 $this->query( $sql );
818 } catch ( Exception
$e ) {
819 $this->scrollableCursor
= true;
822 $this->scrollableCursor
= true;
827 * Makes an encoded list of strings from an array
828 * @param array $a Containing the data
829 * @param int $mode Constant
830 * - LIST_COMMA: comma separated, no field names
831 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
832 * the documentation for $conds in Database::select().
833 * - LIST_OR: ORed WHERE clause (without the WHERE)
834 * - LIST_SET: comma separated with field names, like a SET clause
835 * - LIST_NAMES: comma separated field names
836 * @param array $binaryColumns Contains a list of column names that are binary types
837 * This is a custom parameter only present for MS SQL.
839 * @throws DBUnexpectedError
842 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
843 if ( !is_array( $a ) ) {
844 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
847 if ( $mode != LIST_NAMES
) {
848 // In MS SQL, values need to be specially encoded when they are
849 // inserted into binary fields. Perform this necessary encoding
850 // for the specified set of columns.
851 foreach ( array_keys( $a ) as $field ) {
852 if ( !isset( $binaryColumns[$field] ) ) {
856 if ( is_array( $a[$field] ) ) {
857 foreach ( $a[$field] as &$v ) {
858 $v = new MssqlBlob( $v );
862 $a[$field] = new MssqlBlob( $a[$field] );
867 return parent
::makeList( $a, $mode );
871 * @param string $table
872 * @param string $field
873 * @return int Returns the size of a text field, or -1 for "unlimited"
875 public function textFieldSize( $table, $field ) {
876 $table = $this->tableName( $table );
877 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
878 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
879 $res = $this->query( $sql );
880 $row = $this->fetchRow( $res );
882 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
883 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
890 * Construct a LIMIT query with optional offset
891 * This is used for query pages
893 * @param string $sql SQL query we will append the limit too
894 * @param int $limit The SQL limit
895 * @param bool|int $offset The SQL offset (default false)
896 * @return array|string
897 * @throws DBUnexpectedError
899 public function limitResult( $sql, $limit, $offset = false ) {
900 if ( $offset === false ||
$offset == 0 ) {
901 if ( strpos( $sql, "SELECT" ) === false ) {
902 return "TOP {$limit} " . $sql;
904 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
905 'SELECT$1 TOP ' . $limit, $sql, 1 );
908 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
909 $select = $orderby = [];
910 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
911 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
913 $first = $offset +
1;
914 $last = $offset +
$limit;
915 $sub1 = 'sub_' . $this->subqueryId
;
916 $sub2 = 'sub_' . ( $this->subqueryId +
1 );
917 $this->subqueryId +
= 2;
920 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
924 $overOrder = 'ORDER BY (SELECT 1)';
926 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
927 // don't need to strip it out if we're using a FOR XML clause
928 $sql = str_replace( $orderby[1], '', $sql );
930 $overOrder = $orderby[1];
931 $postOrder = ' ' . $overOrder;
933 $sql = "SELECT {$select[1]}
935 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
936 FROM ({$sql}) {$sub1}
938 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
945 * If there is a limit clause, parse it, strip it, and pass the remaining
946 * SQL through limitResult() with the appropriate parameters. Not the
947 * prettiest solution, but better than building a whole new parser. This
948 * exists becase there are still too many extensions that don't use dynamic
952 * @return array|mixed|string
954 public function LimitToTopN( $sql ) {
955 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
956 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
957 if ( preg_match( $pattern, $sql, $matches ) ) {
958 $row_count = $matches[4];
959 $offset = $matches[3] ?
: $matches[6] ?
: false;
961 // strip the matching LIMIT clause out
962 $sql = str_replace( $matches[0], '', $sql );
964 return $this->limitResult( $sql, $row_count, $offset );
971 * @return string Wikitext of a link to the server software's web site
973 public function getSoftwareLink() {
974 return "[{{int:version-db-mssql-url}} MS SQL Server]";
978 * @return string Version information from the database
980 public function getServerVersion() {
981 $server_info = sqlsrv_server_info( $this->conn
);
982 $version = $server_info['SQLServerVersion'] ??
'Error';
988 * @param string $table
989 * @param string $fname
992 public function tableExists( $table, $fname = __METHOD__
) {
993 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
995 if ( $db !== false ) {
997 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
1001 if ( $schema === false ) {
1002 $schema = $this->dbSchema();
1005 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1006 WHERE TABLE_TYPE = 'BASE TABLE'
1007 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1009 if ( $res->numRows() ) {
1017 * Query whether a given column exists in the mediawiki schema
1018 * @param string $table
1019 * @param string $field
1020 * @param string $fname
1023 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1024 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1026 if ( $db !== false ) {
1028 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1032 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1033 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1035 if ( $res->numRows() ) {
1042 public function fieldInfo( $table, $field ) {
1043 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1045 if ( $db !== false ) {
1047 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1051 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1052 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1054 $meta = $res->fetchRow();
1056 return new MssqlField( $meta );
1062 protected function doSavepoint( $identifier, $fname ) {
1063 $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1066 protected function doReleaseSavepoint( $identifier, $fname ) {
1067 // Not supported. Also not really needed, a new doSavepoint() for the
1068 // same identifier will overwrite the old.
1071 protected function doRollbackToSavepoint( $identifier, $fname ) {
1072 $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1076 * Begin a transaction, committing any previously open transaction
1077 * @param string $fname
1079 protected function doBegin( $fname = __METHOD__
) {
1080 sqlsrv_begin_transaction( $this->conn
);
1081 $this->trxLevel
= 1;
1086 * @param string $fname
1088 protected function doCommit( $fname = __METHOD__
) {
1089 sqlsrv_commit( $this->conn
);
1090 $this->trxLevel
= 0;
1094 * Rollback a transaction.
1095 * No-op on non-transactional databases.
1096 * @param string $fname
1098 protected function doRollback( $fname = __METHOD__
) {
1099 sqlsrv_rollback( $this->conn
);
1100 $this->trxLevel
= 0;
1107 public function strencode( $s ) {
1108 // Should not be called by us
1109 return str_replace( "'", "''", $s );
1113 * @param string|int|null|bool|Blob $s
1114 * @return string|int
1116 public function addQuotes( $s ) {
1117 if ( $s instanceof MssqlBlob
) {
1119 } elseif ( $s instanceof Blob
) {
1120 // this shouldn't really ever be called, but it's here if needed
1121 // (and will quite possibly make the SQL error out)
1122 $blob = new MssqlBlob( $s->fetch() );
1123 return $blob->fetch();
1125 if ( is_bool( $s ) ) {
1128 return parent
::addQuotes( $s );
1136 public function addIdentifierQuotes( $s ) {
1137 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1138 return '[' . $s . ']';
1142 * @param string $name
1145 public function isQuotedIdentifier( $name ) {
1146 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1150 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1153 * @param string $escapeChar
1156 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1157 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1158 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1159 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1163 protected function doSelectDomain( DatabaseDomain
$domain ) {
1164 if ( $domain->getSchema() !== null ) {
1165 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1168 $database = $domain->getDatabase();
1169 if ( $database !== $this->getDBname() ) {
1170 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
1171 list( $res, $err, $errno ) =
1172 $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
1174 if ( $res === false ) {
1175 $this->reportQueryError( $err, $errno, $sql, __METHOD__
);
1176 return false; // unreachable
1179 // Update that domain fields on success (no exception thrown)
1180 $this->currentDomain
= $domain;
1186 * @param array $options An associative array of options to be turned into
1187 * an SQL query, valid keys are listed in the function.
1190 public function makeSelectOptions( $options ) {
1195 foreach ( $options as $key => $option ) {
1196 if ( is_numeric( $key ) ) {
1197 $noKeyOptions[$option] = true;
1201 $tailOpts .= $this->makeGroupByWithHaving( $options );
1203 $tailOpts .= $this->makeOrderBy( $options );
1205 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1206 $startOpts .= 'DISTINCT';
1209 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1210 // used in group concat field emulation
1211 $tailOpts .= " FOR XML PATH('')";
1214 // we want this to be compatible with the output of parent::makeSelectOptions()
1215 return [ $startOpts, '', $tailOpts, '', '' ];
1218 public function getType() {
1223 * @param array $stringList
1226 public function buildConcat( $stringList ) {
1227 return implode( ' + ', $stringList );
1231 * Build a GROUP_CONCAT or equivalent statement for a query.
1232 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1234 * This is useful for combining a field for several rows into a single string.
1235 * NULL values will not appear in the output, duplicated values will appear,
1236 * and the resulting delimiter-separated values have no defined sort order.
1237 * Code using the results may need to use the PHP unique() or sort() methods.
1239 * @param string $delim Glue to bind the results together
1240 * @param string|array $table Table name
1241 * @param string $field Field name
1242 * @param string|array $conds Conditions
1243 * @param string|array $join_conds Join conditions
1244 * @return string SQL text
1247 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1250 $gcsq = 'gcsq_' . $this->subqueryId
;
1251 $this->subqueryId++
;
1253 $delimLen = strlen( $delim );
1254 $fld = "{$field} + {$this->addQuotes( $delim )}";
1255 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1256 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1257 . ") {$gcsq} ({$field}))";
1262 public function buildSubstring( $input, $startPosition, $length = null ) {
1263 $this->assertBuildSubstringParams( $startPosition, $length );
1264 if ( $length === null ) {
1266 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1267 * length returned use the default maximum size of text.
1268 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1270 $length = 2147483647;
1272 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1276 * Returns an associative array for fields that are of type varbinary, binary, or image
1277 * $table can be either a raw table name or passed through tableName() first
1278 * @param string $table
1281 private function getBinaryColumns( $table ) {
1282 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1283 $tableRaw = array_pop( $tableRawArr );
1285 if ( $this->binaryColumnCache
=== null ) {
1286 $this->populateColumnCaches();
1289 return $this->binaryColumnCache
[$tableRaw] ??
[];
1293 * @param string $table
1296 private function getBitColumns( $table ) {
1297 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1298 $tableRaw = array_pop( $tableRawArr );
1300 if ( $this->bitColumnCache
=== null ) {
1301 $this->populateColumnCaches();
1304 return $this->bitColumnCache
[$tableRaw] ??
[];
1307 private function populateColumnCaches() {
1308 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1310 'TABLE_CATALOG' => $this->getDBname(),
1311 'TABLE_SCHEMA' => $this->dbSchema(),
1312 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1315 $this->binaryColumnCache
= [];
1316 $this->bitColumnCache
= [];
1317 foreach ( $res as $row ) {
1318 if ( $row->DATA_TYPE
== 'bit' ) {
1319 $this->bitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1321 $this->binaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1327 * @param string $name
1328 * @param string $format One of "quoted" (default), "raw", or "split".
1329 * @return string|array When the requested $format is "split", a list of database, schema, and
1330 * table name is returned. Database and schema can be `false`.
1332 function tableName( $name, $format = 'quoted' ) {
1333 # Replace reserved words with better ones
1336 return $this->realTableName( 'mwuser', $format );
1338 return $this->realTableName( $name, $format );
1343 * call this instead of tableName() in the updater when renaming tables
1344 * @param string $name
1345 * @param string $format One of "quoted" (default), "raw", or "split".
1346 * @return string|array When the requested $format is "split", a list of database, schema, and
1347 * table name is returned. Database and schema can be `false`.
1350 function realTableName( $name, $format = 'quoted' ) {
1351 $table = parent
::tableName( $name, $format );
1352 if ( $format == 'split' ) {
1353 // Used internally, we want the schema split off from the table name and returned
1354 // as a list with 3 elements (database, schema, table)
1355 return array_pad( explode( '.', $table, 3 ), -3, false );
1362 * @param string $tableName
1363 * @param string $fName
1364 * @return bool|IResultWrapper
1367 public function dropTable( $tableName, $fName = __METHOD__
) {
1368 if ( !$this->tableExists( $tableName, $fName ) ) {
1372 // parent function incorrectly appends CASCADE, which we don't want
1373 $sql = "DROP TABLE " . $this->tableName( $tableName );
1375 return $this->query( $sql, $fName );
1379 * Called in the installer and updater.
1380 * Probably doesn't need to be called anywhere else in the codebase.
1381 * @param bool|null $value
1384 public function prepareStatements( $value = null ) {
1385 $old = $this->prepareStatements
;
1386 if ( $value !== null ) {
1387 $this->prepareStatements
= $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 $old = $this->scrollableCursor
;
1401 if ( $value !== null ) {
1402 $this->scrollableCursor
= $value;
1408 public function buildStringCast( $field ) {
1409 return "CAST( $field AS NVARCHAR )";
1412 public static function getAttributes() {
1413 return [ self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> true ];
1418 * @deprecated since 1.29
1420 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );