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
;
33 use Wikimedia\AtEase\AtEase
;
38 class DatabaseMssql
extends Database
{
40 protected $serverPort;
42 protected $useWindowsAuth = false;
44 protected $lastInsertId = null;
46 protected $lastAffectedRowCount = null;
48 protected $subqueryId = 0;
50 protected $scrollableCursor = true;
52 protected $prepareStatements = true;
53 /** @var stdClass[][]|null */
54 protected $binaryColumnCache = null;
55 /** @var stdClass[][]|null */
56 protected $bitColumnCache = null;
58 protected $ignoreDupKeyErrors = false;
60 protected $ignoreErrors = [];
62 public function implicitGroupby() {
66 public function implicitOrderby() {
70 public function unionSupportsOrderAndLimit() {
74 public function __construct( array $params ) {
75 $this->serverPort
= $params['port'];
76 $this->useWindowsAuth
= $params['UseWindowsAuth'];
78 parent
::__construct( $params );
81 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
82 // Test for driver support, to avoid suppressed fatal error
83 if ( !function_exists( 'sqlsrv_connect' ) ) {
84 throw new DBConnectionError(
86 "Microsoft SQL Server Native (sqlsrv) functions missing.
87 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
92 $this->server
= $server;
94 $this->password
= $password;
98 if ( $dbName != '' ) {
99 $connectionInfo['Database'] = $dbName;
102 // Decide which auth scenerio to use
103 // if we are using Windows auth, then don't add credentials to $connectionInfo
104 if ( !$this->useWindowsAuth
) {
105 $connectionInfo['UID'] = $user;
106 $connectionInfo['PWD'] = $password;
109 AtEase
::suppressWarnings();
110 $this->conn
= sqlsrv_connect( $server, $connectionInfo );
111 AtEase
::restoreWarnings();
113 if ( $this->conn
=== false ) {
114 $error = $this->lastError();
115 $this->connLogger
->error(
116 "Error connecting to {db_server}: {error}",
117 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
119 throw new DBConnectionError( $this, $error );
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;
378 public function serverIsReadOnly() {
379 $encDatabase = $this->addQuotes( $this->getDBname() );
381 "SELECT IS_READ_ONLY FROM SYS.DATABASES WHERE NAME = $encDatabase",
384 $row = $this->fetchObject( $res );
386 return $row ?
(bool)$row->IS_READ_ONLY
: false;
392 protected function fetchAffectedRowCount() {
393 return $this->lastAffectedRowCount
;
399 * @param mixed $table Array or string, table name(s) (prefix auto-added)
400 * @param mixed $vars Array or string, field name(s) to be retrieved
401 * @param mixed $conds Array or string, condition(s) for WHERE
402 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
403 * @param array $options Associative array of options (e.g.
404 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
405 * code for list of supported stuff
406 * @param array $join_conds Associative array of table join conditions
407 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
408 * @return mixed Database result resource (feed to Database::fetchObject
409 * or whatever), or false on failure
410 * @throws DBQueryError
411 * @throws DBUnexpectedError
414 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
415 $options = [], $join_conds = []
417 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
418 if ( isset( $options['EXPLAIN'] ) ) {
420 $this->scrollableCursor
= false;
421 $this->prepareStatements
= false;
422 $this->query( "SET SHOWPLAN_ALL ON" );
423 $ret = $this->query( $sql, $fname );
424 $this->query( "SET SHOWPLAN_ALL OFF" );
425 } catch ( DBQueryError
$dqe ) {
426 if ( isset( $options['FOR COUNT'] ) ) {
427 // likely don't have privs for SHOWPLAN, so run a select count instead
428 $this->query( "SET SHOWPLAN_ALL OFF" );
429 unset( $options['EXPLAIN'] );
430 $ret = $this->select(
432 'COUNT(*) AS EstimateRows',
439 // someone actually wanted the query plan instead of an est row count
440 // let them know of the error
441 $this->scrollableCursor
= true;
442 $this->prepareStatements
= true;
446 $this->scrollableCursor
= true;
447 $this->prepareStatements
= true;
450 return $this->query( $sql, $fname );
456 * @param mixed $table Array or string, table name(s) (prefix auto-added)
457 * @param mixed $vars Array or string, field name(s) to be retrieved
458 * @param mixed $conds Array or string, condition(s) for WHERE
459 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
460 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
461 * see Database::makeSelectOptions code for list of supported stuff
462 * @param array $join_conds Associative array of table join conditions (optional)
463 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
464 * @return string The SQL text
466 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
467 $options = [], $join_conds = []
469 if ( isset( $options['EXPLAIN'] ) ) {
470 unset( $options['EXPLAIN'] );
473 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
475 // try to rewrite aggregations of bit columns (currently MAX and MIN)
476 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
478 if ( is_array( $table ) ) {
481 $t = array_pop( $tables );
482 if ( is_array( $t ) ) {
483 $tables = array_merge( $tables, $t );
485 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
489 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
492 foreach ( $bitColumns as $col => $info ) {
494 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
495 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
497 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
504 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
507 $this->scrollableCursor
= false;
509 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
510 } catch ( Exception
$e ) {
511 $this->scrollableCursor
= true;
514 $this->scrollableCursor
= true;
517 public function delete( $table, $conds, $fname = __METHOD__
) {
518 $this->scrollableCursor
= false;
520 parent
::delete( $table, $conds, $fname );
521 } catch ( Exception
$e ) {
522 $this->scrollableCursor
= true;
525 $this->scrollableCursor
= true;
531 * Estimate rows in dataset
532 * Returns estimated count, based on SHOWPLAN_ALL output
533 * This is not necessarily an accurate estimate, so use sparingly
534 * Returns -1 if count cannot be found
535 * Takes same arguments as Database::select()
536 * @param string $table
538 * @param string $conds
539 * @param string $fname
540 * @param array $options
541 * @param array $join_conds
544 public function estimateRowCount( $table, $var = '*', $conds = '',
545 $fname = __METHOD__
, $options = [], $join_conds = []
547 $conds = $this->normalizeConditions( $conds, $fname );
548 $column = $this->extractSingleFieldFromList( $var );
549 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
550 $conds[] = "$column IS NOT NULL";
553 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
554 $options['EXPLAIN'] = true;
555 $options['FOR COUNT'] = true;
556 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
560 $row = $this->fetchRow( $res );
562 if ( isset( $row['EstimateRows'] ) ) {
563 $rows = (int)$row['EstimateRows'];
571 * Returns information about an index
572 * If errors are explicitly ignored, returns NULL on failure
573 * @param string $table
574 * @param string $index
575 * @param string $fname
576 * @return array|bool|null
578 public function indexInfo( $table, $index, $fname = __METHOD__
) {
579 # This does not return the same info as MYSQL would, but that's OK
580 # because MediaWiki never uses the returned value except to check for
581 # the existence of indexes.
582 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
583 $res = $this->query( $sql, $fname );
590 foreach ( $res as $row ) {
591 if ( $row->index_name
== $index ) {
592 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
593 $cols = explode( ", ", $row->index_keys
);
594 foreach ( $cols as $col ) {
595 $row->Column_name
= trim( $col );
596 $result[] = clone $row;
598 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
599 $row->Non_unique
= 0;
600 $cols = explode( ", ", $row->index_keys
);
601 foreach ( $cols as $col ) {
602 $row->Column_name
= trim( $col );
603 $result[] = clone $row;
608 return $result ?
: false;
612 * INSERT wrapper, inserts an array into a table
614 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
617 * Usually aborts on failure
618 * If errors are explicitly ignored, returns success
619 * @param string $table
620 * @param array $arrToInsert
621 * @param string $fname
622 * @param array $options
626 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
627 # No rows to insert, easy just return now
628 if ( !count( $arrToInsert ) ) {
632 if ( !is_array( $options ) ) {
633 $options = [ $options ];
636 $table = $this->tableName( $table );
638 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
639 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
642 // We know the table we're inserting into, get its identity column
644 // strip matching square brackets and the db/schema from table name
645 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
646 $tableRaw = array_pop( $tableRawArr );
647 $res = $this->doQuery(
648 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
649 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
651 if ( $res && sqlsrv_has_rows( $res ) ) {
652 // There is an identity for this table.
653 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
654 $identity = array_pop( $identityArr );
656 sqlsrv_free_stmt( $res );
658 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
659 $binaryColumns = $this->getBinaryColumns( $table );
661 // INSERT IGNORE is not supported by SQL Server
662 // remove IGNORE from options list and set ignore flag to true
663 if ( in_array( 'IGNORE', $options ) ) {
664 $options = array_diff( $options, [ 'IGNORE' ] );
665 $this->ignoreDupKeyErrors
= true;
669 foreach ( $arrToInsert as $a ) {
670 // start out with empty identity column, this is so we can return
671 // it as a result of the INSERT logic
674 $identityClause = '';
676 // if we have an identity column
679 foreach ( $a as $k => $v ) {
680 if ( $k == $identity ) {
681 if ( !is_null( $v ) ) {
682 // there is a value being passed to us,
683 // we need to turn on and off inserted identity
684 $sqlPre = "SET IDENTITY_INSERT $table ON;";
685 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
687 // we can't insert NULL into an identity column,
688 // so remove the column from the insert.
694 // we want to output an identity column as result
695 $identityClause = "OUTPUT INSERTED.$identity ";
698 $keys = array_keys( $a );
700 // Build the actual query
701 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
702 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
705 foreach ( $a as $key => $value ) {
706 if ( isset( $binaryColumns[$key] ) ) {
707 $value = new MssqlBlob( $value );
714 if ( is_null( $value ) ) {
717 $sql .= $this->addQuotes( $value );
720 $sql .= ')' . $sqlPost;
723 $this->scrollableCursor
= false;
725 $ret = $this->query( $sql );
726 } catch ( Exception
$e ) {
727 $this->scrollableCursor
= true;
728 $this->ignoreDupKeyErrors
= false;
731 $this->scrollableCursor
= true;
733 if ( $ret instanceof ResultWrapper
&& !is_null( $identity ) ) {
734 // Then we want to get the identity column value we were assigned and save it off
735 $row = $ret->fetchObject();
736 if ( is_object( $row ) ) {
737 $this->lastInsertId
= $row->$identity;
738 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
739 // used if we got an identity back, we know for sure a row was affected, so
741 if ( $this->lastAffectedRowCount
== -1 ) {
742 $this->lastAffectedRowCount
= 1;
748 $this->ignoreDupKeyErrors
= false;
754 * INSERT SELECT wrapper
755 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
756 * Source items may be literals rather than field names, but strings should
757 * be quoted with Database::addQuotes().
758 * @param string $destTable
759 * @param array|string $srcTable May be an array of tables.
760 * @param array $varMap
761 * @param array $conds May be "*" to copy the whole table.
762 * @param string $fname
763 * @param array $insertOptions
764 * @param array $selectOptions
765 * @param array $selectJoinConds
768 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
769 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
771 $this->scrollableCursor
= false;
773 parent
::nativeInsertSelect(
783 } catch ( Exception
$e ) {
784 $this->scrollableCursor
= true;
787 $this->scrollableCursor
= true;
791 * UPDATE wrapper. Takes a condition array and a SET array.
793 * @param string $table Name of the table to UPDATE. This will be passed through
794 * Database::tableName().
796 * @param array $values An array of values to SET. For each array element,
797 * the key gives the field name, and the value gives the data
798 * to set that field to. The data will be quoted by
799 * Database::addQuotes().
801 * @param array $conds An array of conditions (WHERE). See
802 * Database::select() for the details of the format of
803 * condition arrays. Use '*' to update all rows.
805 * @param string $fname The function name of the caller (from __METHOD__),
806 * for logging and profiling.
808 * @param array $options An array of UPDATE options, can be:
809 * - IGNORE: Ignore unique key conflicts
810 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
812 * @throws DBUnexpectedError
815 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
816 $table = $this->tableName( $table );
817 $binaryColumns = $this->getBinaryColumns( $table );
819 $opts = $this->makeUpdateOptions( $options );
820 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
822 if ( $conds !== [] && $conds !== '*' ) {
823 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
826 $this->scrollableCursor
= false;
828 $this->query( $sql );
829 } catch ( Exception
$e ) {
830 $this->scrollableCursor
= true;
833 $this->scrollableCursor
= true;
838 * Makes an encoded list of strings from an array
839 * @param array $a Containing the data
840 * @param int $mode Constant
841 * - LIST_COMMA: comma separated, no field names
842 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
843 * the documentation for $conds in Database::select().
844 * - LIST_OR: ORed WHERE clause (without the WHERE)
845 * - LIST_SET: comma separated with field names, like a SET clause
846 * - LIST_NAMES: comma separated field names
847 * @param array $binaryColumns Contains a list of column names that are binary types
848 * This is a custom parameter only present for MS SQL.
850 * @throws DBUnexpectedError
853 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
854 if ( !is_array( $a ) ) {
855 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
858 if ( $mode != LIST_NAMES
) {
859 // In MS SQL, values need to be specially encoded when they are
860 // inserted into binary fields. Perform this necessary encoding
861 // for the specified set of columns.
862 foreach ( array_keys( $a ) as $field ) {
863 if ( !isset( $binaryColumns[$field] ) ) {
867 if ( is_array( $a[$field] ) ) {
868 foreach ( $a[$field] as &$v ) {
869 $v = new MssqlBlob( $v );
873 $a[$field] = new MssqlBlob( $a[$field] );
878 return parent
::makeList( $a, $mode );
882 * @param string $table
883 * @param string $field
884 * @return int Returns the size of a text field, or -1 for "unlimited"
886 public function textFieldSize( $table, $field ) {
887 $table = $this->tableName( $table );
888 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
889 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
890 $res = $this->query( $sql );
891 $row = $this->fetchRow( $res );
893 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
894 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
901 * Construct a LIMIT query with optional offset
902 * This is used for query pages
904 * @param string $sql SQL query we will append the limit too
905 * @param int $limit The SQL limit
906 * @param bool|int $offset The SQL offset (default false)
907 * @return array|string
908 * @throws DBUnexpectedError
910 public function limitResult( $sql, $limit, $offset = false ) {
911 if ( $offset === false ||
$offset == 0 ) {
912 if ( strpos( $sql, "SELECT" ) === false ) {
913 return "TOP {$limit} " . $sql;
915 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
916 'SELECT$1 TOP ' . $limit, $sql, 1 );
919 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
920 $select = $orderby = [];
921 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
922 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
924 $first = $offset +
1;
925 $last = $offset +
$limit;
926 $sub1 = 'sub_' . $this->subqueryId
;
927 $sub2 = 'sub_' . ( $this->subqueryId +
1 );
928 $this->subqueryId +
= 2;
931 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
935 $overOrder = 'ORDER BY (SELECT 1)';
937 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
938 // don't need to strip it out if we're using a FOR XML clause
939 $sql = str_replace( $orderby[1], '', $sql );
941 $overOrder = $orderby[1];
942 $postOrder = ' ' . $overOrder;
944 $sql = "SELECT {$select[1]}
946 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
947 FROM ({$sql}) {$sub1}
949 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
956 * If there is a limit clause, parse it, strip it, and pass the remaining
957 * SQL through limitResult() with the appropriate parameters. Not the
958 * prettiest solution, but better than building a whole new parser. This
959 * exists becase there are still too many extensions that don't use dynamic
963 * @return array|mixed|string
965 public function LimitToTopN( $sql ) {
966 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
967 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
968 if ( preg_match( $pattern, $sql, $matches ) ) {
969 $row_count = $matches[4];
970 $offset = $matches[3] ?
: $matches[6] ?
: false;
972 // strip the matching LIMIT clause out
973 $sql = str_replace( $matches[0], '', $sql );
975 return $this->limitResult( $sql, $row_count, $offset );
982 * @return string Wikitext of a link to the server software's web site
984 public function getSoftwareLink() {
985 return "[{{int:version-db-mssql-url}} MS SQL Server]";
989 * @return string Version information from the database
991 public function getServerVersion() {
992 $server_info = sqlsrv_server_info( $this->conn
);
993 $version = $server_info['SQLServerVersion'] ??
'Error';
999 * @param string $table
1000 * @param string $fname
1003 public function tableExists( $table, $fname = __METHOD__
) {
1004 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1006 if ( $db !== false ) {
1008 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
1012 if ( $schema === false ) {
1013 $schema = $this->dbSchema();
1016 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1017 WHERE TABLE_TYPE = 'BASE TABLE'
1018 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1020 if ( $res->numRows() ) {
1028 * Query whether a given column exists in the mediawiki schema
1029 * @param string $table
1030 * @param string $field
1031 * @param string $fname
1034 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1035 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1037 if ( $db !== false ) {
1039 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1043 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1044 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1046 if ( $res->numRows() ) {
1053 public function fieldInfo( $table, $field ) {
1054 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1056 if ( $db !== false ) {
1058 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1062 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1063 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1065 $meta = $res->fetchRow();
1067 return new MssqlField( $meta );
1073 protected function doSavepoint( $identifier, $fname ) {
1074 $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1077 protected function doReleaseSavepoint( $identifier, $fname ) {
1078 // Not supported. Also not really needed, a new doSavepoint() for the
1079 // same identifier will overwrite the old.
1082 protected function doRollbackToSavepoint( $identifier, $fname ) {
1083 $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1086 protected function doBegin( $fname = __METHOD__
) {
1087 if ( !sqlsrv_begin_transaction( $this->conn
) ) {
1088 $this->reportQueryError( $this->lastError(), $this->lastErrno(), 'BEGIN', $fname );
1094 * @param string $fname
1096 protected function doCommit( $fname = __METHOD__
) {
1097 if ( !sqlsrv_commit( $this->conn
) ) {
1098 $this->reportQueryError( $this->lastError(), $this->lastErrno(), 'COMMIT', $fname );
1103 * Rollback a transaction.
1104 * No-op on non-transactional databases.
1105 * @param string $fname
1107 protected function doRollback( $fname = __METHOD__
) {
1108 if ( !sqlsrv_rollback( $this->conn
) ) {
1109 $this->queryLogger
->error(
1110 "{fname}\t{db_server}\t{errno}\t{error}\t",
1111 $this->getLogContext( [
1112 'errno' => $this->lastErrno(),
1113 'error' => $this->lastError(),
1115 'trace' => ( new RuntimeException() )->getTraceAsString()
1125 public function strencode( $s ) {
1126 // Should not be called by us
1127 return str_replace( "'", "''", $s );
1131 * @param string|int|null|bool|Blob $s
1132 * @return string|int
1134 public function addQuotes( $s ) {
1135 if ( $s instanceof MssqlBlob
) {
1137 } elseif ( $s instanceof Blob
) {
1138 // this shouldn't really ever be called, but it's here if needed
1139 // (and will quite possibly make the SQL error out)
1140 $blob = new MssqlBlob( $s->fetch() );
1141 return $blob->fetch();
1143 if ( is_bool( $s ) ) {
1146 return parent
::addQuotes( $s );
1154 public function addIdentifierQuotes( $s ) {
1155 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1156 return '[' . $s . ']';
1160 * @param string $name
1163 public function isQuotedIdentifier( $name ) {
1164 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1168 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1171 * @param string $escapeChar
1174 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1175 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1176 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1177 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1181 protected function doSelectDomain( DatabaseDomain
$domain ) {
1182 if ( $domain->getSchema() !== null ) {
1183 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1186 $database = $domain->getDatabase();
1187 if ( $database !== $this->getDBname() ) {
1188 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
1189 list( $res, $err, $errno ) =
1190 $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
1192 if ( $res === false ) {
1193 $this->reportQueryError( $err, $errno, $sql, __METHOD__
);
1194 return false; // unreachable
1197 // Update that domain fields on success (no exception thrown)
1198 $this->currentDomain
= $domain;
1204 * @param array $options An associative array of options to be turned into
1205 * an SQL query, valid keys are listed in the function.
1208 public function makeSelectOptions( $options ) {
1213 foreach ( $options as $key => $option ) {
1214 if ( is_numeric( $key ) ) {
1215 $noKeyOptions[$option] = true;
1219 $tailOpts .= $this->makeGroupByWithHaving( $options );
1221 $tailOpts .= $this->makeOrderBy( $options );
1223 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1224 $startOpts .= 'DISTINCT';
1227 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1228 // used in group concat field emulation
1229 $tailOpts .= " FOR XML PATH('')";
1232 // we want this to be compatible with the output of parent::makeSelectOptions()
1233 return [ $startOpts, '', $tailOpts, '', '' ];
1236 public function getType() {
1241 * @param array $stringList
1244 public function buildConcat( $stringList ) {
1245 return implode( ' + ', $stringList );
1249 * Build a GROUP_CONCAT or equivalent statement for a query.
1250 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1252 * This is useful for combining a field for several rows into a single string.
1253 * NULL values will not appear in the output, duplicated values will appear,
1254 * and the resulting delimiter-separated values have no defined sort order.
1255 * Code using the results may need to use the PHP unique() or sort() methods.
1257 * @param string $delim Glue to bind the results together
1258 * @param string|array $table Table name
1259 * @param string $field Field name
1260 * @param string|array $conds Conditions
1261 * @param string|array $join_conds Join conditions
1262 * @return string SQL text
1265 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1268 $gcsq = 'gcsq_' . $this->subqueryId
;
1269 $this->subqueryId++
;
1271 $delimLen = strlen( $delim );
1272 $fld = "{$field} + {$this->addQuotes( $delim )}";
1273 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1274 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1275 . ") {$gcsq} ({$field}))";
1280 public function buildSubstring( $input, $startPosition, $length = null ) {
1281 $this->assertBuildSubstringParams( $startPosition, $length );
1282 if ( $length === null ) {
1284 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1285 * length returned use the default maximum size of text.
1286 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1288 $length = 2147483647;
1290 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1294 * Returns an associative array for fields that are of type varbinary, binary, or image
1295 * $table can be either a raw table name or passed through tableName() first
1296 * @param string $table
1299 private function getBinaryColumns( $table ) {
1300 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1301 $tableRaw = array_pop( $tableRawArr );
1303 if ( $this->binaryColumnCache
=== null ) {
1304 $this->populateColumnCaches();
1307 return $this->binaryColumnCache
[$tableRaw] ??
[];
1311 * @param string $table
1314 private function getBitColumns( $table ) {
1315 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1316 $tableRaw = array_pop( $tableRawArr );
1318 if ( $this->bitColumnCache
=== null ) {
1319 $this->populateColumnCaches();
1322 return $this->bitColumnCache
[$tableRaw] ??
[];
1325 private function populateColumnCaches() {
1326 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1328 'TABLE_CATALOG' => $this->getDBname(),
1329 'TABLE_SCHEMA' => $this->dbSchema(),
1330 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1333 $this->binaryColumnCache
= [];
1334 $this->bitColumnCache
= [];
1335 foreach ( $res as $row ) {
1336 if ( $row->DATA_TYPE
== 'bit' ) {
1337 $this->bitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1339 $this->binaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1345 * @param string $name
1346 * @param string $format One of "quoted" (default), "raw", or "split".
1347 * @return string|array When the requested $format is "split", a list of database, schema, and
1348 * table name is returned. Database and schema can be `false`.
1350 function tableName( $name, $format = 'quoted' ) {
1351 # Replace reserved words with better ones
1354 return $this->realTableName( 'mwuser', $format );
1356 return $this->realTableName( $name, $format );
1361 * call this instead of tableName() in the updater when renaming tables
1362 * @param string $name
1363 * @param string $format One of "quoted" (default), "raw", or "split".
1364 * @return string|array When the requested $format is "split", a list of database, schema, and
1365 * table name is returned. Database and schema can be `false`.
1368 function realTableName( $name, $format = 'quoted' ) {
1369 $table = parent
::tableName( $name, $format );
1370 if ( $format == 'split' ) {
1371 // Used internally, we want the schema split off from the table name and returned
1372 // as a list with 3 elements (database, schema, table)
1373 return array_pad( explode( '.', $table, 3 ), -3, false );
1380 * @param string $tableName
1381 * @param string $fName
1382 * @return bool|IResultWrapper
1385 public function dropTable( $tableName, $fName = __METHOD__
) {
1386 if ( !$this->tableExists( $tableName, $fName ) ) {
1390 // parent function incorrectly appends CASCADE, which we don't want
1391 $sql = "DROP TABLE " . $this->tableName( $tableName );
1393 return $this->query( $sql, $fName );
1397 * Called in the installer and updater.
1398 * Probably doesn't need to be called anywhere else in the codebase.
1399 * @param bool|null $value
1402 public function prepareStatements( $value = null ) {
1403 $old = $this->prepareStatements
;
1404 if ( $value !== null ) {
1405 $this->prepareStatements
= $value;
1412 * Called in the installer and updater.
1413 * Probably doesn't need to be called anywhere else in the codebase.
1414 * @param bool|null $value
1417 public function scrollableCursor( $value = null ) {
1418 $old = $this->scrollableCursor
;
1419 if ( $value !== null ) {
1420 $this->scrollableCursor
= $value;
1426 public function buildStringCast( $field ) {
1427 return "CAST( $field AS NVARCHAR )";
1430 public static function getAttributes() {
1431 return [ self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> true ];
1436 * @deprecated since 1.29
1438 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );