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 if ( !function_exists( 'sqlsrv_connect' ) ) {
83 throw new DBConnectionError(
85 "Microsoft SQL Server Native (sqlsrv) functions missing.\n
86 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470"
92 if ( $schema !== null ) {
93 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
96 $this->server
= $server;
98 $this->password
= $password;
100 $connectionInfo = [];
101 if ( strlen( $dbName ) ) {
102 $connectionInfo['Database'] = $dbName;
104 if ( !$this->useWindowsAuth
) {
105 $connectionInfo['UID'] = $user;
106 $connectionInfo['PWD'] = $password;
109 AtEase
::suppressWarnings();
110 $this->conn
= sqlsrv_connect( $server, $connectionInfo ) ?
: null;
111 AtEase
::restoreWarnings();
113 if ( !$this->conn
) {
114 throw $this->newExceptionAfterConnectError( $this->lastError() );
118 $this->currentDomain
= new DatabaseDomain(
119 strlen( $dbName ) ?
$dbName : null,
123 } catch ( Exception
$e ) {
124 throw $this->newExceptionAfterConnectError( $e->getMessage() );
129 * Closes a database connection, if it is open
130 * Returns success, true if already closed
133 protected function closeConnection() {
134 return sqlsrv_close( $this->conn
);
138 * @param bool|MssqlResultWrapper|resource $result
139 * @return bool|MssqlResultWrapper
141 protected function resultObject( $result ) {
144 } elseif ( $result instanceof MssqlResultWrapper
) {
146 } elseif ( $result === true ) {
147 // Successful write query
150 return new MssqlResultWrapper( $this, $result );
156 * @return bool|MssqlResultWrapper|resource
158 protected function doQuery( $sql ) {
159 // several extensions seem to think that all databases support limits
160 // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
161 // so to catch any of those extensions we'll do a quick check for a
162 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
163 // the LIMIT clause and passes the result to $this->limitResult();
164 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
165 // massage LIMIT -> TopN
166 $sql = $this->LimitToTopN( $sql );
169 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
170 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
171 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
172 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
177 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
178 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
179 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
180 // strings make php throw a fatal error "Severe error translating Unicode"
181 if ( $this->scrollableCursor
) {
182 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
187 if ( $this->prepareStatements
) {
188 // we do prepare + execute so we can get its field metadata for later usage if desired
189 $stmt = sqlsrv_prepare( $this->conn
, $sql, [], $scrollArr );
190 $success = sqlsrv_execute( $stmt );
192 $stmt = sqlsrv_query( $this->conn
, $sql, [], $scrollArr );
193 $success = (bool)$stmt;
196 // Make a copy to ensure what we add below does not get reflected in future queries
197 $ignoreErrors = $this->ignoreErrors
;
199 if ( $this->ignoreDupKeyErrors
) {
200 // ignore duplicate key errors
201 // this emulates INSERT IGNORE in MySQL
202 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
203 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
204 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
207 if ( $success === false ) {
208 $errors = sqlsrv_errors();
211 foreach ( $errors as $err ) {
212 if ( !in_array( $err['code'], $ignoreErrors ) ) {
218 if ( $success === false ) {
222 // remember number of rows affected
223 $this->lastAffectedRowCount
= sqlsrv_rows_affected( $stmt );
228 public function freeResult( $res ) {
229 sqlsrv_free_stmt( ResultWrapper
::unwrap( $res ) );
233 * @param IResultWrapper $res
236 public function fetchObject( $res ) {
237 // $res is expected to be an instance of MssqlResultWrapper here
238 return $res->fetchObject();
242 * @param IResultWrapper $res
245 public function fetchRow( $res ) {
246 return $res->fetchRow();
253 public function numRows( $res ) {
254 $res = ResultWrapper
::unwrap( $res );
256 $ret = sqlsrv_num_rows( $res );
257 if ( $ret === false ) {
258 // we cannot get an amount of rows from this cursor type
259 // has_rows returns bool true/false if the result has rows
260 $ret = (int)sqlsrv_has_rows( $res );
270 public function numFields( $res ) {
271 return sqlsrv_num_fields( ResultWrapper
::unwrap( $res ) );
279 public function fieldName( $res, $n ) {
280 return sqlsrv_field_metadata( ResultWrapper
::unwrap( $res ) )[$n]['Name'];
284 * This must be called after nextSequenceVal
287 public function insertId() {
288 return $this->lastInsertId
;
292 * @param MssqlResultWrapper $res
296 public function dataSeek( $res, $row ) {
297 return $res->seek( $row );
303 public function lastError() {
305 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
306 if ( $retErrors != null ) {
307 foreach ( $retErrors as $arrError ) {
308 $strRet .= $this->formatError( $arrError ) . "\n";
311 $strRet = "No errors found";
321 private function formatError( $err ) {
322 return '[SQLSTATE ' .
323 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
329 public function lastErrno() {
330 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
331 if ( $err !== null && isset( $err[0] ) ) {
332 return $err[0]['code'];
338 protected function wasKnownStatementRollbackError() {
339 $errors = sqlsrv_errors( SQLSRV_ERR_ALL
);
343 // The transaction vs statement rollback behavior depends on XACT_ABORT, so make sure
344 // that the "statement has been terminated" error (3621) is specifically present.
345 // https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql
346 $statementOnly = false;
347 $codeWhitelist = [ '2601', '2627', '547' ];
348 foreach ( $errors as $error ) {
349 if ( $error['code'] == '3621' ) {
350 $statementOnly = true;
351 } elseif ( !in_array( $error['code'], $codeWhitelist ) ) {
352 $statementOnly = false;
357 return $statementOnly;
360 public function serverIsReadOnly() {
361 $encDatabase = $this->addQuotes( $this->getDBname() );
363 "SELECT IS_READ_ONLY FROM SYS.DATABASES WHERE NAME = $encDatabase",
366 $row = $this->fetchObject( $res );
368 return $row ?
(bool)$row->IS_READ_ONLY
: false;
374 protected function fetchAffectedRowCount() {
375 return $this->lastAffectedRowCount
;
381 * @param mixed $table Array or string, table name(s) (prefix auto-added)
382 * @param mixed $vars Array or string, field name(s) to be retrieved
383 * @param mixed $conds Array or string, condition(s) for WHERE
384 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
385 * @param array $options Associative array of options (e.g.
386 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
387 * code for list of supported stuff
388 * @param array $join_conds Associative array of table join conditions
389 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
390 * @return mixed Database result resource (feed to Database::fetchObject
391 * or whatever), or false on failure
392 * @throws DBQueryError
393 * @throws DBUnexpectedError
396 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
397 $options = [], $join_conds = []
399 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
400 if ( isset( $options['EXPLAIN'] ) ) {
402 $this->scrollableCursor
= false;
403 $this->prepareStatements
= false;
404 $this->query( "SET SHOWPLAN_ALL ON" );
405 $ret = $this->query( $sql, $fname );
406 $this->query( "SET SHOWPLAN_ALL OFF" );
407 } catch ( DBQueryError
$dqe ) {
408 if ( isset( $options['FOR COUNT'] ) ) {
409 // likely don't have privs for SHOWPLAN, so run a select count instead
410 $this->query( "SET SHOWPLAN_ALL OFF" );
411 unset( $options['EXPLAIN'] );
412 $ret = $this->select(
414 'COUNT(*) AS EstimateRows',
421 // someone actually wanted the query plan instead of an est row count
422 // let them know of the error
423 $this->scrollableCursor
= true;
424 $this->prepareStatements
= true;
428 $this->scrollableCursor
= true;
429 $this->prepareStatements
= true;
432 return $this->query( $sql, $fname );
438 * @param mixed $table Array or string, table name(s) (prefix auto-added)
439 * @param mixed $vars Array or string, field name(s) to be retrieved
440 * @param mixed $conds Array or string, condition(s) for WHERE
441 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
442 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
443 * see Database::makeSelectOptions code for list of supported stuff
444 * @param array $join_conds Associative array of table join conditions (optional)
445 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
446 * @return string The SQL text
448 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
449 $options = [], $join_conds = []
451 if ( isset( $options['EXPLAIN'] ) ) {
452 unset( $options['EXPLAIN'] );
455 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
457 // try to rewrite aggregations of bit columns (currently MAX and MIN)
458 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
460 if ( is_array( $table ) ) {
463 $t = array_pop( $tables );
464 if ( is_array( $t ) ) {
465 $tables = array_merge( $tables, $t );
467 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
471 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
474 foreach ( $bitColumns as $col => $info ) {
476 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
477 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
479 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
486 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
489 $this->scrollableCursor
= false;
491 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
492 } catch ( Exception
$e ) {
493 $this->scrollableCursor
= true;
496 $this->scrollableCursor
= true;
499 public function delete( $table, $conds, $fname = __METHOD__
) {
500 $this->scrollableCursor
= false;
502 parent
::delete( $table, $conds, $fname );
503 } catch ( Exception
$e ) {
504 $this->scrollableCursor
= true;
507 $this->scrollableCursor
= true;
513 * Estimate rows in dataset
514 * Returns estimated count, based on SHOWPLAN_ALL output
515 * This is not necessarily an accurate estimate, so use sparingly
516 * Returns -1 if count cannot be found
517 * Takes same arguments as Database::select()
518 * @param string $table
520 * @param string $conds
521 * @param string $fname
522 * @param array $options
523 * @param array $join_conds
526 public function estimateRowCount( $table, $var = '*', $conds = '',
527 $fname = __METHOD__
, $options = [], $join_conds = []
529 $conds = $this->normalizeConditions( $conds, $fname );
530 $column = $this->extractSingleFieldFromList( $var );
531 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
532 $conds[] = "$column IS NOT NULL";
535 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
536 $options['EXPLAIN'] = true;
537 $options['FOR COUNT'] = true;
538 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
542 $row = $this->fetchRow( $res );
544 if ( isset( $row['EstimateRows'] ) ) {
545 $rows = (int)$row['EstimateRows'];
553 * Returns information about an index
554 * If errors are explicitly ignored, returns NULL on failure
555 * @param string $table
556 * @param string $index
557 * @param string $fname
558 * @return array|bool|null
560 public function indexInfo( $table, $index, $fname = __METHOD__
) {
561 # This does not return the same info as MYSQL would, but that's OK
562 # because MediaWiki never uses the returned value except to check for
563 # the existence of indexes.
564 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
565 $res = $this->query( $sql, $fname );
572 foreach ( $res as $row ) {
573 if ( $row->index_name
== $index ) {
574 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
575 $cols = explode( ", ", $row->index_keys
);
576 foreach ( $cols as $col ) {
577 $row->Column_name
= trim( $col );
578 $result[] = clone $row;
580 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
581 $row->Non_unique
= 0;
582 $cols = explode( ", ", $row->index_keys
);
583 foreach ( $cols as $col ) {
584 $row->Column_name
= trim( $col );
585 $result[] = clone $row;
590 return $result ?
: false;
594 * INSERT wrapper, inserts an array into a table
596 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
599 * Usually aborts on failure
600 * If errors are explicitly ignored, returns success
601 * @param string $table
602 * @param array $arrToInsert
603 * @param string $fname
604 * @param array $options
608 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
609 # No rows to insert, easy just return now
610 if ( !count( $arrToInsert ) ) {
614 if ( !is_array( $options ) ) {
615 $options = [ $options ];
618 $table = $this->tableName( $table );
620 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
621 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
624 // We know the table we're inserting into, get its identity column
626 // strip matching square brackets and the db/schema from table name
627 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
628 $tableRaw = array_pop( $tableRawArr );
629 $res = $this->doQuery(
630 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
631 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
633 if ( $res && sqlsrv_has_rows( $res ) ) {
634 // There is an identity for this table.
635 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
636 $identity = array_pop( $identityArr );
638 sqlsrv_free_stmt( $res );
640 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
641 $binaryColumns = $this->getBinaryColumns( $table );
643 // INSERT IGNORE is not supported by SQL Server
644 // remove IGNORE from options list and set ignore flag to true
645 if ( in_array( 'IGNORE', $options ) ) {
646 $options = array_diff( $options, [ 'IGNORE' ] );
647 $this->ignoreDupKeyErrors
= true;
651 foreach ( $arrToInsert as $a ) {
652 // start out with empty identity column, this is so we can return
653 // it as a result of the INSERT logic
656 $identityClause = '';
658 // if we have an identity column
661 foreach ( $a as $k => $v ) {
662 if ( $k == $identity ) {
663 if ( !is_null( $v ) ) {
664 // there is a value being passed to us,
665 // we need to turn on and off inserted identity
666 $sqlPre = "SET IDENTITY_INSERT $table ON;";
667 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
669 // we can't insert NULL into an identity column,
670 // so remove the column from the insert.
676 // we want to output an identity column as result
677 $identityClause = "OUTPUT INSERTED.$identity ";
680 $keys = array_keys( $a );
682 // Build the actual query
683 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
684 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
687 foreach ( $a as $key => $value ) {
688 if ( isset( $binaryColumns[$key] ) ) {
689 $value = new MssqlBlob( $value );
696 if ( is_null( $value ) ) {
699 $sql .= $this->addQuotes( $value );
702 $sql .= ')' . $sqlPost;
705 $this->scrollableCursor
= false;
707 $ret = $this->query( $sql );
708 } catch ( Exception
$e ) {
709 $this->scrollableCursor
= true;
710 $this->ignoreDupKeyErrors
= false;
713 $this->scrollableCursor
= true;
715 if ( $ret instanceof IResultWrapper
&& !is_null( $identity ) ) {
716 // Then we want to get the identity column value we were assigned and save it off
717 $row = $ret->fetchObject();
718 if ( is_object( $row ) ) {
719 $this->lastInsertId
= $row->$identity;
720 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
721 // used if we got an identity back, we know for sure a row was affected, so
723 if ( $this->lastAffectedRowCount
== -1 ) {
724 $this->lastAffectedRowCount
= 1;
730 $this->ignoreDupKeyErrors
= false;
736 * INSERT SELECT wrapper
737 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
738 * Source items may be literals rather than field names, but strings should
739 * be quoted with Database::addQuotes().
740 * @param string $destTable
741 * @param array|string $srcTable May be an array of tables.
742 * @param array $varMap
743 * @param array $conds May be "*" to copy the whole table.
744 * @param string $fname
745 * @param array $insertOptions
746 * @param array $selectOptions
747 * @param array $selectJoinConds
750 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
751 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
753 $this->scrollableCursor
= false;
755 parent
::nativeInsertSelect(
765 } catch ( Exception
$e ) {
766 $this->scrollableCursor
= true;
769 $this->scrollableCursor
= true;
773 * UPDATE wrapper. Takes a condition array and a SET array.
775 * @param string $table Name of the table to UPDATE. This will be passed through
776 * Database::tableName().
778 * @param array $values An array of values to SET. For each array element,
779 * the key gives the field name, and the value gives the data
780 * to set that field to. The data will be quoted by
781 * Database::addQuotes().
783 * @param array $conds An array of conditions (WHERE). See
784 * Database::select() for the details of the format of
785 * condition arrays. Use '*' to update all rows.
787 * @param string $fname The function name of the caller (from __METHOD__),
788 * for logging and profiling.
790 * @param array $options An array of UPDATE options, can be:
791 * - IGNORE: Ignore unique key conflicts
792 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
794 * @throws DBUnexpectedError
797 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
798 $table = $this->tableName( $table );
799 $binaryColumns = $this->getBinaryColumns( $table );
801 $opts = $this->makeUpdateOptions( $options );
802 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
804 if ( $conds !== [] && $conds !== '*' ) {
805 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
808 $this->scrollableCursor
= false;
810 $this->query( $sql );
811 } catch ( Exception
$e ) {
812 $this->scrollableCursor
= true;
815 $this->scrollableCursor
= true;
820 * Makes an encoded list of strings from an array
821 * @param array $a Containing the data
822 * @param int $mode Constant
823 * - LIST_COMMA: comma separated, no field names
824 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
825 * the documentation for $conds in Database::select().
826 * - LIST_OR: ORed WHERE clause (without the WHERE)
827 * - LIST_SET: comma separated with field names, like a SET clause
828 * - LIST_NAMES: comma separated field names
829 * @param array $binaryColumns Contains a list of column names that are binary types
830 * This is a custom parameter only present for MS SQL.
832 * @throws DBUnexpectedError
835 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
836 if ( !is_array( $a ) ) {
837 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
840 if ( $mode != LIST_NAMES
) {
841 // In MS SQL, values need to be specially encoded when they are
842 // inserted into binary fields. Perform this necessary encoding
843 // for the specified set of columns.
844 foreach ( array_keys( $a ) as $field ) {
845 if ( !isset( $binaryColumns[$field] ) ) {
849 if ( is_array( $a[$field] ) ) {
850 foreach ( $a[$field] as &$v ) {
851 $v = new MssqlBlob( $v );
855 $a[$field] = new MssqlBlob( $a[$field] );
860 return parent
::makeList( $a, $mode );
864 * @param string $table
865 * @param string $field
866 * @return int Returns the size of a text field, or -1 for "unlimited"
868 public function textFieldSize( $table, $field ) {
869 $table = $this->tableName( $table );
870 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
871 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
872 $res = $this->query( $sql );
873 $row = $this->fetchRow( $res );
875 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
876 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
883 * Construct a LIMIT query with optional offset
884 * This is used for query pages
886 * @param string $sql SQL query we will append the limit too
887 * @param int $limit The SQL limit
888 * @param bool|int $offset The SQL offset (default false)
889 * @return array|string
890 * @throws DBUnexpectedError
892 public function limitResult( $sql, $limit, $offset = false ) {
893 if ( $offset === false ||
$offset == 0 ) {
894 if ( strpos( $sql, "SELECT" ) === false ) {
895 return "TOP {$limit} " . $sql;
897 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
898 'SELECT$1 TOP ' . $limit, $sql, 1 );
901 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
902 $select = $orderby = [];
903 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
904 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
906 $first = $offset +
1;
907 $last = $offset +
$limit;
908 $sub1 = 'sub_' . $this->subqueryId
;
909 $sub2 = 'sub_' . ( $this->subqueryId +
1 );
910 $this->subqueryId +
= 2;
913 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
917 $overOrder = 'ORDER BY (SELECT 1)';
919 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
920 // don't need to strip it out if we're using a FOR XML clause
921 $sql = str_replace( $orderby[1], '', $sql );
923 $overOrder = $orderby[1];
924 $postOrder = ' ' . $overOrder;
926 $sql = "SELECT {$select[1]}
928 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
929 FROM ({$sql}) {$sub1}
931 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
938 * If there is a limit clause, parse it, strip it, and pass the remaining
939 * SQL through limitResult() with the appropriate parameters. Not the
940 * prettiest solution, but better than building a whole new parser. This
941 * exists becase there are still too many extensions that don't use dynamic
945 * @return array|mixed|string
947 public function LimitToTopN( $sql ) {
948 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
949 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
950 if ( preg_match( $pattern, $sql, $matches ) ) {
951 $row_count = $matches[4];
952 $offset = $matches[3] ?
: $matches[6] ?
: false;
954 // strip the matching LIMIT clause out
955 $sql = str_replace( $matches[0], '', $sql );
957 return $this->limitResult( $sql, $row_count, $offset );
964 * @return string Wikitext of a link to the server software's web site
966 public function getSoftwareLink() {
967 return "[{{int:version-db-mssql-url}} MS SQL Server]";
971 * @return string Version information from the database
973 public function getServerVersion() {
974 $server_info = sqlsrv_server_info( $this->conn
);
975 $version = $server_info['SQLServerVersion'] ??
'Error';
981 * @param string $table
982 * @param string $fname
985 public function tableExists( $table, $fname = __METHOD__
) {
986 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
988 if ( $db !== false ) {
990 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
994 if ( $schema === false ) {
995 $schema = $this->dbSchema();
998 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
999 WHERE TABLE_TYPE = 'BASE TABLE'
1000 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1002 if ( $res->numRows() ) {
1010 * Query whether a given column exists in the mediawiki schema
1011 * @param string $table
1012 * @param string $field
1013 * @param string $fname
1016 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1017 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1019 if ( $db !== false ) {
1021 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1025 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1026 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1028 if ( $res->numRows() ) {
1035 public function fieldInfo( $table, $field ) {
1036 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1038 if ( $db !== false ) {
1040 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1044 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1045 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1047 $meta = $res->fetchRow();
1049 return new MssqlField( $meta );
1055 protected function doSavepoint( $identifier, $fname ) {
1056 $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1059 protected function doReleaseSavepoint( $identifier, $fname ) {
1060 // Not supported. Also not really needed, a new doSavepoint() for the
1061 // same identifier will overwrite the old.
1064 protected function doRollbackToSavepoint( $identifier, $fname ) {
1065 $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1068 protected function doBegin( $fname = __METHOD__
) {
1069 if ( !sqlsrv_begin_transaction( $this->conn
) ) {
1070 $this->reportQueryError( $this->lastError(), $this->lastErrno(), 'BEGIN', $fname );
1076 * @param string $fname
1078 protected function doCommit( $fname = __METHOD__
) {
1079 if ( !sqlsrv_commit( $this->conn
) ) {
1080 $this->reportQueryError( $this->lastError(), $this->lastErrno(), 'COMMIT', $fname );
1085 * Rollback a transaction.
1086 * No-op on non-transactional databases.
1087 * @param string $fname
1089 protected function doRollback( $fname = __METHOD__
) {
1090 if ( !sqlsrv_rollback( $this->conn
) ) {
1091 $this->queryLogger
->error(
1092 "{fname}\t{db_server}\t{errno}\t{error}\t",
1093 $this->getLogContext( [
1094 'errno' => $this->lastErrno(),
1095 'error' => $this->lastError(),
1097 'trace' => ( new RuntimeException() )->getTraceAsString()
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(
1167 __CLASS__
. ": domain '{$domain->getId()}' has a schema component"
1171 $database = $domain->getDatabase();
1172 if ( $database !== $this->getDBname() ) {
1173 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
1174 list( $res, $err, $errno ) =
1175 $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
1177 if ( $res === false ) {
1178 $this->reportQueryError( $err, $errno, $sql, __METHOD__
);
1179 return false; // unreachable
1182 // Update that domain fields on success (no exception thrown)
1183 $this->currentDomain
= $domain;
1189 * @param array $options An associative array of options to be turned into
1190 * an SQL query, valid keys are listed in the function.
1193 public function makeSelectOptions( $options ) {
1198 foreach ( $options as $key => $option ) {
1199 if ( is_numeric( $key ) ) {
1200 $noKeyOptions[$option] = true;
1204 $tailOpts .= $this->makeGroupByWithHaving( $options );
1206 $tailOpts .= $this->makeOrderBy( $options );
1208 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1209 $startOpts .= 'DISTINCT';
1212 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1213 // used in group concat field emulation
1214 $tailOpts .= " FOR XML PATH('')";
1217 // we want this to be compatible with the output of parent::makeSelectOptions()
1218 return [ $startOpts, '', $tailOpts, '', '' ];
1221 public function getType() {
1226 * @param array $stringList
1229 public function buildConcat( $stringList ) {
1230 return implode( ' + ', $stringList );
1234 * Build a GROUP_CONCAT or equivalent statement for a query.
1235 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1237 * This is useful for combining a field for several rows into a single string.
1238 * NULL values will not appear in the output, duplicated values will appear,
1239 * and the resulting delimiter-separated values have no defined sort order.
1240 * Code using the results may need to use the PHP unique() or sort() methods.
1242 * @param string $delim Glue to bind the results together
1243 * @param string|array $table Table name
1244 * @param string $field Field name
1245 * @param string|array $conds Conditions
1246 * @param string|array $join_conds Join conditions
1247 * @return string SQL text
1250 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1253 $gcsq = 'gcsq_' . $this->subqueryId
;
1254 $this->subqueryId++
;
1256 $delimLen = strlen( $delim );
1257 $fld = "{$field} + {$this->addQuotes( $delim )}";
1258 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1259 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1260 . ") {$gcsq} ({$field}))";
1265 public function buildSubstring( $input, $startPosition, $length = null ) {
1266 $this->assertBuildSubstringParams( $startPosition, $length );
1267 if ( $length === null ) {
1269 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1270 * length returned use the default maximum size of text.
1271 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1273 $length = 2147483647;
1275 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1279 * Returns an associative array for fields that are of type varbinary, binary, or image
1280 * $table can be either a raw table name or passed through tableName() first
1281 * @param string $table
1284 private function getBinaryColumns( $table ) {
1285 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1286 $tableRaw = array_pop( $tableRawArr );
1288 if ( $this->binaryColumnCache
=== null ) {
1289 $this->populateColumnCaches();
1292 return $this->binaryColumnCache
[$tableRaw] ??
[];
1296 * @param string $table
1299 private function getBitColumns( $table ) {
1300 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1301 $tableRaw = array_pop( $tableRawArr );
1303 if ( $this->bitColumnCache
=== null ) {
1304 $this->populateColumnCaches();
1307 return $this->bitColumnCache
[$tableRaw] ??
[];
1310 private function populateColumnCaches() {
1311 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1313 'TABLE_CATALOG' => $this->getDBname(),
1314 'TABLE_SCHEMA' => $this->dbSchema(),
1315 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1318 $this->binaryColumnCache
= [];
1319 $this->bitColumnCache
= [];
1320 foreach ( $res as $row ) {
1321 if ( $row->DATA_TYPE
== 'bit' ) {
1322 $this->bitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1324 $this->binaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1330 * @param string $name
1331 * @param string $format One of "quoted" (default), "raw", or "split".
1332 * @return string|array When the requested $format is "split", a list of database, schema, and
1333 * table name is returned. Database and schema can be `false`.
1335 function tableName( $name, $format = 'quoted' ) {
1336 # Replace reserved words with better ones
1339 return $this->realTableName( 'mwuser', $format );
1341 return $this->realTableName( $name, $format );
1346 * call this instead of tableName() in the updater when renaming tables
1347 * @param string $name
1348 * @param string $format One of "quoted" (default), "raw", or "split".
1349 * @return string|array When the requested $format is "split", a list of database, schema, and
1350 * table name is returned. Database and schema can be `false`.
1353 function realTableName( $name, $format = 'quoted' ) {
1354 $table = parent
::tableName( $name, $format );
1355 if ( $format == 'split' ) {
1356 // Used internally, we want the schema split off from the table name and returned
1357 // as a list with 3 elements (database, schema, table)
1358 return array_pad( explode( '.', $table, 3 ), -3, false );
1365 * @param string $tableName
1366 * @param string $fName
1367 * @return bool|IResultWrapper
1370 public function dropTable( $tableName, $fName = __METHOD__
) {
1371 if ( !$this->tableExists( $tableName, $fName ) ) {
1375 // parent function incorrectly appends CASCADE, which we don't want
1376 $sql = "DROP TABLE " . $this->tableName( $tableName );
1378 return $this->query( $sql, $fName );
1382 * Called in the installer and updater.
1383 * Probably doesn't need to be called anywhere else in the codebase.
1384 * @param bool|null $value
1387 public function prepareStatements( $value = null ) {
1388 $old = $this->prepareStatements
;
1389 if ( $value !== null ) {
1390 $this->prepareStatements
= $value;
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 scrollableCursor( $value = null ) {
1403 $old = $this->scrollableCursor
;
1404 if ( $value !== null ) {
1405 $this->scrollableCursor
= $value;
1411 public function buildStringCast( $field ) {
1412 return "CAST( $field AS NVARCHAR )";
1415 public static function getAttributes() {
1416 return [ self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> true ];
1421 * @deprecated since 1.29
1423 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );