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
;
32 use Wikimedia\AtEase\AtEase
;
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"
91 $this->server
= $server;
93 $this->password
= $password;
97 if ( $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->useWindowsAuth
) {
104 $connectionInfo['UID'] = $user;
105 $connectionInfo['PWD'] = $password;
108 AtEase
::suppressWarnings();
109 $this->conn
= sqlsrv_connect( $server, $connectionInfo );
110 AtEase
::restoreWarnings();
112 if ( $this->conn
=== false ) {
113 $error = $this->lastError();
114 $this->connLogger
->error(
115 "Error connecting to {db_server}: {error}",
116 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
118 throw new DBConnectionError( $this, $error );
121 $this->currentDomain
= new DatabaseDomain(
122 ( $dbName != '' ) ?
$dbName : null,
127 return (bool)$this->conn
;
131 * Closes a database connection, if it is open
132 * Returns success, true if already closed
135 protected function closeConnection() {
136 return sqlsrv_close( $this->conn
);
140 * @param bool|MssqlResultWrapper|resource $result
141 * @return bool|MssqlResultWrapper
143 protected function resultObject( $result ) {
146 } elseif ( $result instanceof MssqlResultWrapper
) {
148 } elseif ( $result === true ) {
149 // Successful write query
152 return new MssqlResultWrapper( $this, $result );
158 * @return bool|MssqlResultWrapper|resource
160 protected function doQuery( $sql ) {
161 // several extensions seem to think that all databases support limits
162 // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
163 // so to catch any of those extensions we'll do a quick check for a
164 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
165 // the LIMIT clause and passes the result to $this->limitResult();
166 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
167 // massage LIMIT -> TopN
168 $sql = $this->LimitToTopN( $sql );
171 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
172 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
173 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
174 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
179 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
180 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
181 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
182 // strings make php throw a fatal error "Severe error translating Unicode"
183 if ( $this->scrollableCursor
) {
184 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
189 if ( $this->prepareStatements
) {
190 // we do prepare + execute so we can get its field metadata for later usage if desired
191 $stmt = sqlsrv_prepare( $this->conn
, $sql, [], $scrollArr );
192 $success = sqlsrv_execute( $stmt );
194 $stmt = sqlsrv_query( $this->conn
, $sql, [], $scrollArr );
195 $success = (bool)$stmt;
198 // Make a copy to ensure what we add below does not get reflected in future queries
199 $ignoreErrors = $this->ignoreErrors
;
201 if ( $this->ignoreDupKeyErrors
) {
202 // ignore duplicate key errors
203 // this emulates INSERT IGNORE in MySQL
204 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
205 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
206 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
209 if ( $success === false ) {
210 $errors = sqlsrv_errors();
213 foreach ( $errors as $err ) {
214 if ( !in_array( $err['code'], $ignoreErrors ) ) {
220 if ( $success === false ) {
224 // remember number of rows affected
225 $this->lastAffectedRowCount
= sqlsrv_rows_affected( $stmt );
230 public function freeResult( $res ) {
231 if ( $res instanceof ResultWrapper
) {
235 sqlsrv_free_stmt( $res );
239 * @param IResultWrapper $res
242 public function fetchObject( $res ) {
243 // $res is expected to be an instance of MssqlResultWrapper here
244 return $res->fetchObject();
248 * @param IResultWrapper $res
251 public function fetchRow( $res ) {
252 return $res->fetchRow();
259 public function numRows( $res ) {
260 if ( $res instanceof ResultWrapper
) {
264 $ret = sqlsrv_num_rows( $res );
266 if ( $ret === false ) {
267 // we cannot get an amount of rows from this cursor type
268 // has_rows returns bool true/false if the result has rows
269 $ret = (int)sqlsrv_has_rows( $res );
279 public function numFields( $res ) {
280 if ( $res instanceof ResultWrapper
) {
284 return sqlsrv_num_fields( $res );
292 public function fieldName( $res, $n ) {
293 if ( $res instanceof ResultWrapper
) {
297 return sqlsrv_field_metadata( $res )[$n]['Name'];
301 * This must be called after nextSequenceVal
304 public function insertId() {
305 return $this->lastInsertId
;
309 * @param MssqlResultWrapper $res
313 public function dataSeek( $res, $row ) {
314 return $res->seek( $row );
320 public function lastError() {
322 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
323 if ( $retErrors != null ) {
324 foreach ( $retErrors as $arrError ) {
325 $strRet .= $this->formatError( $arrError ) . "\n";
328 $strRet = "No errors found";
338 private function formatError( $err ) {
339 return '[SQLSTATE ' .
340 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
346 public function lastErrno() {
347 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
348 if ( $err !== null && isset( $err[0] ) ) {
349 return $err[0]['code'];
355 protected function wasKnownStatementRollbackError() {
356 $errors = sqlsrv_errors( SQLSRV_ERR_ALL
);
360 // The transaction vs statement rollback behavior depends on XACT_ABORT, so make sure
361 // that the "statement has been terminated" error (3621) is specifically present.
362 // https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql
363 $statementOnly = false;
364 $codeWhitelist = [ '2601', '2627', '547' ];
365 foreach ( $errors as $error ) {
366 if ( $error['code'] == '3621' ) {
367 $statementOnly = true;
368 } elseif ( !in_array( $error['code'], $codeWhitelist ) ) {
369 $statementOnly = false;
374 return $statementOnly;
380 protected function fetchAffectedRowCount() {
381 return $this->lastAffectedRowCount
;
387 * @param mixed $table Array or string, table name(s) (prefix auto-added)
388 * @param mixed $vars Array or string, field name(s) to be retrieved
389 * @param mixed $conds Array or string, condition(s) for WHERE
390 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
391 * @param array $options Associative array of options (e.g.
392 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
393 * code for list of supported stuff
394 * @param array $join_conds Associative array of table join conditions
395 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
396 * @return mixed Database result resource (feed to Database::fetchObject
397 * or whatever), or false on failure
398 * @throws DBQueryError
399 * @throws DBUnexpectedError
402 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
403 $options = [], $join_conds = []
405 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
406 if ( isset( $options['EXPLAIN'] ) ) {
408 $this->scrollableCursor
= false;
409 $this->prepareStatements
= false;
410 $this->query( "SET SHOWPLAN_ALL ON" );
411 $ret = $this->query( $sql, $fname );
412 $this->query( "SET SHOWPLAN_ALL OFF" );
413 } catch ( DBQueryError
$dqe ) {
414 if ( isset( $options['FOR COUNT'] ) ) {
415 // likely don't have privs for SHOWPLAN, so run a select count instead
416 $this->query( "SET SHOWPLAN_ALL OFF" );
417 unset( $options['EXPLAIN'] );
418 $ret = $this->select(
420 'COUNT(*) AS EstimateRows',
427 // someone actually wanted the query plan instead of an est row count
428 // let them know of the error
429 $this->scrollableCursor
= true;
430 $this->prepareStatements
= true;
434 $this->scrollableCursor
= true;
435 $this->prepareStatements
= true;
438 return $this->query( $sql, $fname );
444 * @param mixed $table Array or string, table name(s) (prefix auto-added)
445 * @param mixed $vars Array or string, field name(s) to be retrieved
446 * @param mixed $conds Array or string, condition(s) for WHERE
447 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
448 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
449 * see Database::makeSelectOptions code for list of supported stuff
450 * @param array $join_conds Associative array of table join conditions (optional)
451 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
452 * @return string The SQL text
454 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
455 $options = [], $join_conds = []
457 if ( isset( $options['EXPLAIN'] ) ) {
458 unset( $options['EXPLAIN'] );
461 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
463 // try to rewrite aggregations of bit columns (currently MAX and MIN)
464 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
466 if ( is_array( $table ) ) {
469 $t = array_pop( $tables );
470 if ( is_array( $t ) ) {
471 $tables = array_merge( $tables, $t );
473 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
477 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
480 foreach ( $bitColumns as $col => $info ) {
482 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
483 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
485 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
492 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
495 $this->scrollableCursor
= false;
497 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
498 } catch ( Exception
$e ) {
499 $this->scrollableCursor
= true;
502 $this->scrollableCursor
= true;
505 public function delete( $table, $conds, $fname = __METHOD__
) {
506 $this->scrollableCursor
= false;
508 parent
::delete( $table, $conds, $fname );
509 } catch ( Exception
$e ) {
510 $this->scrollableCursor
= true;
513 $this->scrollableCursor
= true;
519 * Estimate rows in dataset
520 * Returns estimated count, based on SHOWPLAN_ALL output
521 * This is not necessarily an accurate estimate, so use sparingly
522 * Returns -1 if count cannot be found
523 * Takes same arguments as Database::select()
524 * @param string $table
526 * @param string $conds
527 * @param string $fname
528 * @param array $options
529 * @param array $join_conds
532 public function estimateRowCount( $table, $var = '*', $conds = '',
533 $fname = __METHOD__
, $options = [], $join_conds = []
535 $conds = $this->normalizeConditions( $conds, $fname );
536 $column = $this->extractSingleFieldFromList( $var );
537 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
538 $conds[] = "$column IS NOT NULL";
541 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
542 $options['EXPLAIN'] = true;
543 $options['FOR COUNT'] = true;
544 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
548 $row = $this->fetchRow( $res );
550 if ( isset( $row['EstimateRows'] ) ) {
551 $rows = (int)$row['EstimateRows'];
559 * Returns information about an index
560 * If errors are explicitly ignored, returns NULL on failure
561 * @param string $table
562 * @param string $index
563 * @param string $fname
564 * @return array|bool|null
566 public function indexInfo( $table, $index, $fname = __METHOD__
) {
567 # This does not return the same info as MYSQL would, but that's OK
568 # because MediaWiki never uses the returned value except to check for
569 # the existence of indexes.
570 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
571 $res = $this->query( $sql, $fname );
578 foreach ( $res as $row ) {
579 if ( $row->index_name
== $index ) {
580 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
581 $cols = explode( ", ", $row->index_keys
);
582 foreach ( $cols as $col ) {
583 $row->Column_name
= trim( $col );
584 $result[] = clone $row;
586 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
587 $row->Non_unique
= 0;
588 $cols = explode( ", ", $row->index_keys
);
589 foreach ( $cols as $col ) {
590 $row->Column_name
= trim( $col );
591 $result[] = clone $row;
596 return $result ?
: false;
600 * INSERT wrapper, inserts an array into a table
602 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
605 * Usually aborts on failure
606 * If errors are explicitly ignored, returns success
607 * @param string $table
608 * @param array $arrToInsert
609 * @param string $fname
610 * @param array $options
614 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
615 # No rows to insert, easy just return now
616 if ( !count( $arrToInsert ) ) {
620 if ( !is_array( $options ) ) {
621 $options = [ $options ];
624 $table = $this->tableName( $table );
626 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
627 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
630 // We know the table we're inserting into, get its identity column
632 // strip matching square brackets and the db/schema from table name
633 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
634 $tableRaw = array_pop( $tableRawArr );
635 $res = $this->doQuery(
636 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
637 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
639 if ( $res && sqlsrv_has_rows( $res ) ) {
640 // There is an identity for this table.
641 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
642 $identity = array_pop( $identityArr );
644 sqlsrv_free_stmt( $res );
646 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
647 $binaryColumns = $this->getBinaryColumns( $table );
649 // INSERT IGNORE is not supported by SQL Server
650 // remove IGNORE from options list and set ignore flag to true
651 if ( in_array( 'IGNORE', $options ) ) {
652 $options = array_diff( $options, [ 'IGNORE' ] );
653 $this->ignoreDupKeyErrors
= true;
657 foreach ( $arrToInsert as $a ) {
658 // start out with empty identity column, this is so we can return
659 // it as a result of the INSERT logic
662 $identityClause = '';
664 // if we have an identity column
667 foreach ( $a as $k => $v ) {
668 if ( $k == $identity ) {
669 if ( !is_null( $v ) ) {
670 // there is a value being passed to us,
671 // we need to turn on and off inserted identity
672 $sqlPre = "SET IDENTITY_INSERT $table ON;";
673 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
675 // we can't insert NULL into an identity column,
676 // so remove the column from the insert.
682 // we want to output an identity column as result
683 $identityClause = "OUTPUT INSERTED.$identity ";
686 $keys = array_keys( $a );
688 // Build the actual query
689 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
690 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
693 foreach ( $a as $key => $value ) {
694 if ( isset( $binaryColumns[$key] ) ) {
695 $value = new MssqlBlob( $value );
702 if ( is_null( $value ) ) {
705 $sql .= $this->addQuotes( $value );
708 $sql .= ')' . $sqlPost;
711 $this->scrollableCursor
= false;
713 $ret = $this->query( $sql );
714 } catch ( Exception
$e ) {
715 $this->scrollableCursor
= true;
716 $this->ignoreDupKeyErrors
= false;
719 $this->scrollableCursor
= true;
721 if ( $ret instanceof ResultWrapper
&& !is_null( $identity ) ) {
722 // Then we want to get the identity column value we were assigned and save it off
723 $row = $ret->fetchObject();
724 if ( is_object( $row ) ) {
725 $this->lastInsertId
= $row->$identity;
726 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
727 // used if we got an identity back, we know for sure a row was affected, so
729 if ( $this->lastAffectedRowCount
== -1 ) {
730 $this->lastAffectedRowCount
= 1;
736 $this->ignoreDupKeyErrors
= false;
742 * INSERT SELECT wrapper
743 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
744 * Source items may be literals rather than field names, but strings should
745 * be quoted with Database::addQuotes().
746 * @param string $destTable
747 * @param array|string $srcTable May be an array of tables.
748 * @param array $varMap
749 * @param array $conds May be "*" to copy the whole table.
750 * @param string $fname
751 * @param array $insertOptions
752 * @param array $selectOptions
753 * @param array $selectJoinConds
756 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
757 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
759 $this->scrollableCursor
= false;
761 parent
::nativeInsertSelect(
771 } catch ( Exception
$e ) {
772 $this->scrollableCursor
= true;
775 $this->scrollableCursor
= true;
779 * UPDATE wrapper. Takes a condition array and a SET array.
781 * @param string $table Name of the table to UPDATE. This will be passed through
782 * Database::tableName().
784 * @param array $values An array of values to SET. For each array element,
785 * the key gives the field name, and the value gives the data
786 * to set that field to. The data will be quoted by
787 * Database::addQuotes().
789 * @param array $conds An array of conditions (WHERE). See
790 * Database::select() for the details of the format of
791 * condition arrays. Use '*' to update all rows.
793 * @param string $fname The function name of the caller (from __METHOD__),
794 * for logging and profiling.
796 * @param array $options An array of UPDATE options, can be:
797 * - IGNORE: Ignore unique key conflicts
798 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
800 * @throws DBUnexpectedError
803 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
804 $table = $this->tableName( $table );
805 $binaryColumns = $this->getBinaryColumns( $table );
807 $opts = $this->makeUpdateOptions( $options );
808 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
810 if ( $conds !== [] && $conds !== '*' ) {
811 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
814 $this->scrollableCursor
= false;
816 $this->query( $sql );
817 } catch ( Exception
$e ) {
818 $this->scrollableCursor
= true;
821 $this->scrollableCursor
= true;
826 * Makes an encoded list of strings from an array
827 * @param array $a Containing the data
828 * @param int $mode Constant
829 * - LIST_COMMA: comma separated, no field names
830 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
831 * the documentation for $conds in Database::select().
832 * - LIST_OR: ORed WHERE clause (without the WHERE)
833 * - LIST_SET: comma separated with field names, like a SET clause
834 * - LIST_NAMES: comma separated field names
835 * @param array $binaryColumns Contains a list of column names that are binary types
836 * This is a custom parameter only present for MS SQL.
838 * @throws DBUnexpectedError
841 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
842 if ( !is_array( $a ) ) {
843 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
846 if ( $mode != LIST_NAMES
) {
847 // In MS SQL, values need to be specially encoded when they are
848 // inserted into binary fields. Perform this necessary encoding
849 // for the specified set of columns.
850 foreach ( array_keys( $a ) as $field ) {
851 if ( !isset( $binaryColumns[$field] ) ) {
855 if ( is_array( $a[$field] ) ) {
856 foreach ( $a[$field] as &$v ) {
857 $v = new MssqlBlob( $v );
861 $a[$field] = new MssqlBlob( $a[$field] );
866 return parent
::makeList( $a, $mode );
870 * @param string $table
871 * @param string $field
872 * @return int Returns the size of a text field, or -1 for "unlimited"
874 public function textFieldSize( $table, $field ) {
875 $table = $this->tableName( $table );
876 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
877 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
878 $res = $this->query( $sql );
879 $row = $this->fetchRow( $res );
881 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
882 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
889 * Construct a LIMIT query with optional offset
890 * This is used for query pages
892 * @param string $sql SQL query we will append the limit too
893 * @param int $limit The SQL limit
894 * @param bool|int $offset The SQL offset (default false)
895 * @return array|string
896 * @throws DBUnexpectedError
898 public function limitResult( $sql, $limit, $offset = false ) {
899 if ( $offset === false ||
$offset == 0 ) {
900 if ( strpos( $sql, "SELECT" ) === false ) {
901 return "TOP {$limit} " . $sql;
903 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
904 'SELECT$1 TOP ' . $limit, $sql, 1 );
907 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
908 $select = $orderby = [];
909 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
910 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
912 $first = $offset +
1;
913 $last = $offset +
$limit;
914 $sub1 = 'sub_' . $this->subqueryId
;
915 $sub2 = 'sub_' . ( $this->subqueryId +
1 );
916 $this->subqueryId +
= 2;
919 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
923 $overOrder = 'ORDER BY (SELECT 1)';
925 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
926 // don't need to strip it out if we're using a FOR XML clause
927 $sql = str_replace( $orderby[1], '', $sql );
929 $overOrder = $orderby[1];
930 $postOrder = ' ' . $overOrder;
932 $sql = "SELECT {$select[1]}
934 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
935 FROM ({$sql}) {$sub1}
937 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
944 * If there is a limit clause, parse it, strip it, and pass the remaining
945 * SQL through limitResult() with the appropriate parameters. Not the
946 * prettiest solution, but better than building a whole new parser. This
947 * exists becase there are still too many extensions that don't use dynamic
951 * @return array|mixed|string
953 public function LimitToTopN( $sql ) {
954 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
955 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
956 if ( preg_match( $pattern, $sql, $matches ) ) {
957 $row_count = $matches[4];
958 $offset = $matches[3] ?
: $matches[6] ?
: false;
960 // strip the matching LIMIT clause out
961 $sql = str_replace( $matches[0], '', $sql );
963 return $this->limitResult( $sql, $row_count, $offset );
970 * @return string Wikitext of a link to the server software's web site
972 public function getSoftwareLink() {
973 return "[{{int:version-db-mssql-url}} MS SQL Server]";
977 * @return string Version information from the database
979 public function getServerVersion() {
980 $server_info = sqlsrv_server_info( $this->conn
);
981 $version = $server_info['SQLServerVersion'] ??
'Error';
987 * @param string $table
988 * @param string $fname
991 public function tableExists( $table, $fname = __METHOD__
) {
992 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
994 if ( $db !== false ) {
996 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
1000 if ( $schema === false ) {
1001 $schema = $this->dbSchema();
1004 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1005 WHERE TABLE_TYPE = 'BASE TABLE'
1006 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1008 if ( $res->numRows() ) {
1016 * Query whether a given column exists in the mediawiki schema
1017 * @param string $table
1018 * @param string $field
1019 * @param string $fname
1022 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1023 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1025 if ( $db !== false ) {
1027 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1031 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1032 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1034 if ( $res->numRows() ) {
1041 public function fieldInfo( $table, $field ) {
1042 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1044 if ( $db !== false ) {
1046 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1050 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1051 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1053 $meta = $res->fetchRow();
1055 return new MssqlField( $meta );
1061 protected function doSavepoint( $identifier, $fname ) {
1062 $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1065 protected function doReleaseSavepoint( $identifier, $fname ) {
1066 // Not supported. Also not really needed, a new doSavepoint() for the
1067 // same identifier will overwrite the old.
1070 protected function doRollbackToSavepoint( $identifier, $fname ) {
1071 $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1075 * Begin a transaction, committing any previously open transaction
1076 * @param string $fname
1078 protected function doBegin( $fname = __METHOD__
) {
1079 sqlsrv_begin_transaction( $this->conn
);
1080 $this->trxLevel
= 1;
1085 * @param string $fname
1087 protected function doCommit( $fname = __METHOD__
) {
1088 sqlsrv_commit( $this->conn
);
1089 $this->trxLevel
= 0;
1093 * Rollback a transaction.
1094 * No-op on non-transactional databases.
1095 * @param string $fname
1097 protected function doRollback( $fname = __METHOD__
) {
1098 sqlsrv_rollback( $this->conn
);
1099 $this->trxLevel
= 0;
1106 public function strencode( $s ) {
1107 // Should not be called by us
1108 return str_replace( "'", "''", $s );
1112 * @param string|int|null|bool|Blob $s
1113 * @return string|int
1115 public function addQuotes( $s ) {
1116 if ( $s instanceof MssqlBlob
) {
1118 } elseif ( $s instanceof Blob
) {
1119 // this shouldn't really ever be called, but it's here if needed
1120 // (and will quite possibly make the SQL error out)
1121 $blob = new MssqlBlob( $s->fetch() );
1122 return $blob->fetch();
1124 if ( is_bool( $s ) ) {
1127 return parent
::addQuotes( $s );
1135 public function addIdentifierQuotes( $s ) {
1136 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1137 return '[' . $s . ']';
1141 * @param string $name
1144 public function isQuotedIdentifier( $name ) {
1145 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1149 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1152 * @param string $escapeChar
1155 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1156 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1157 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1158 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1162 protected function doSelectDomain( DatabaseDomain
$domain ) {
1163 if ( $domain->getSchema() !== null ) {
1164 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1167 $database = $domain->getDatabase();
1168 if ( $database !== $this->getDBname() ) {
1169 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
1170 list( $res, $err, $errno ) =
1171 $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
1173 if ( $res === false ) {
1174 $this->reportQueryError( $err, $errno, $sql, __METHOD__
);
1175 return false; // unreachable
1178 // Update that domain fields on success (no exception thrown)
1179 $this->currentDomain
= $domain;
1185 * @param array $options An associative array of options to be turned into
1186 * an SQL query, valid keys are listed in the function.
1189 public function makeSelectOptions( $options ) {
1194 foreach ( $options as $key => $option ) {
1195 if ( is_numeric( $key ) ) {
1196 $noKeyOptions[$option] = true;
1200 $tailOpts .= $this->makeGroupByWithHaving( $options );
1202 $tailOpts .= $this->makeOrderBy( $options );
1204 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1205 $startOpts .= 'DISTINCT';
1208 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1209 // used in group concat field emulation
1210 $tailOpts .= " FOR XML PATH('')";
1213 // we want this to be compatible with the output of parent::makeSelectOptions()
1214 return [ $startOpts, '', $tailOpts, '', '' ];
1217 public function getType() {
1222 * @param array $stringList
1225 public function buildConcat( $stringList ) {
1226 return implode( ' + ', $stringList );
1230 * Build a GROUP_CONCAT or equivalent statement for a query.
1231 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1233 * This is useful for combining a field for several rows into a single string.
1234 * NULL values will not appear in the output, duplicated values will appear,
1235 * and the resulting delimiter-separated values have no defined sort order.
1236 * Code using the results may need to use the PHP unique() or sort() methods.
1238 * @param string $delim Glue to bind the results together
1239 * @param string|array $table Table name
1240 * @param string $field Field name
1241 * @param string|array $conds Conditions
1242 * @param string|array $join_conds Join conditions
1243 * @return string SQL text
1246 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1249 $gcsq = 'gcsq_' . $this->subqueryId
;
1250 $this->subqueryId++
;
1252 $delimLen = strlen( $delim );
1253 $fld = "{$field} + {$this->addQuotes( $delim )}";
1254 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1255 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1256 . ") {$gcsq} ({$field}))";
1261 public function buildSubstring( $input, $startPosition, $length = null ) {
1262 $this->assertBuildSubstringParams( $startPosition, $length );
1263 if ( $length === null ) {
1265 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1266 * length returned use the default maximum size of text.
1267 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1269 $length = 2147483647;
1271 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1275 * Returns an associative array for fields that are of type varbinary, binary, or image
1276 * $table can be either a raw table name or passed through tableName() first
1277 * @param string $table
1280 private function getBinaryColumns( $table ) {
1281 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1282 $tableRaw = array_pop( $tableRawArr );
1284 if ( $this->binaryColumnCache
=== null ) {
1285 $this->populateColumnCaches();
1288 return $this->binaryColumnCache
[$tableRaw] ??
[];
1292 * @param string $table
1295 private function getBitColumns( $table ) {
1296 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1297 $tableRaw = array_pop( $tableRawArr );
1299 if ( $this->bitColumnCache
=== null ) {
1300 $this->populateColumnCaches();
1303 return $this->bitColumnCache
[$tableRaw] ??
[];
1306 private function populateColumnCaches() {
1307 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1309 'TABLE_CATALOG' => $this->getDBname(),
1310 'TABLE_SCHEMA' => $this->dbSchema(),
1311 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1314 $this->binaryColumnCache
= [];
1315 $this->bitColumnCache
= [];
1316 foreach ( $res as $row ) {
1317 if ( $row->DATA_TYPE
== 'bit' ) {
1318 $this->bitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1320 $this->binaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1326 * @param string $name
1327 * @param string $format One of "quoted" (default), "raw", or "split".
1328 * @return string|array When the requested $format is "split", a list of database, schema, and
1329 * table name is returned. Database and schema can be `false`.
1331 function tableName( $name, $format = 'quoted' ) {
1332 # Replace reserved words with better ones
1335 return $this->realTableName( 'mwuser', $format );
1337 return $this->realTableName( $name, $format );
1342 * call this instead of tableName() in the updater when renaming tables
1343 * @param string $name
1344 * @param string $format One of "quoted" (default), "raw", or "split".
1345 * @return string|array When the requested $format is "split", a list of database, schema, and
1346 * table name is returned. Database and schema can be `false`.
1349 function realTableName( $name, $format = 'quoted' ) {
1350 $table = parent
::tableName( $name, $format );
1351 if ( $format == 'split' ) {
1352 // Used internally, we want the schema split off from the table name and returned
1353 // as a list with 3 elements (database, schema, table)
1354 return array_pad( explode( '.', $table, 3 ), -3, false );
1361 * @param string $tableName
1362 * @param string $fName
1363 * @return bool|IResultWrapper
1366 public function dropTable( $tableName, $fName = __METHOD__
) {
1367 if ( !$this->tableExists( $tableName, $fName ) ) {
1371 // parent function incorrectly appends CASCADE, which we don't want
1372 $sql = "DROP TABLE " . $this->tableName( $tableName );
1374 return $this->query( $sql, $fName );
1378 * Called in the installer and updater.
1379 * Probably doesn't need to be called anywhere else in the codebase.
1380 * @param bool|null $value
1383 public function prepareStatements( $value = null ) {
1384 $old = $this->prepareStatements
;
1385 if ( $value !== null ) {
1386 $this->prepareStatements
= $value;
1393 * Called in the installer and updater.
1394 * Probably doesn't need to be called anywhere else in the codebase.
1395 * @param bool|null $value
1398 public function scrollableCursor( $value = null ) {
1399 $old = $this->scrollableCursor
;
1400 if ( $value !== null ) {
1401 $this->scrollableCursor
= $value;
1407 public function buildStringCast( $field ) {
1408 return "CAST( $field AS NVARCHAR )";
1411 public static function getAttributes() {
1412 return [ self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> true ];
1417 * @deprecated since 1.29
1419 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );