3 * This is the MS SQL Server Native database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author Joel Penner <a-joelpe at microsoft dot com>
23 * @author Chris Pucci <a-cpucci at microsoft dot com>
24 * @author Ryan Biesemeyer <v-ryanbi at microsoft dot com>
25 * @author Ryan Schmidt <skizzerz at gmail dot com>
28 namespace Wikimedia\Rdbms
;
37 class DatabaseMssql
extends Database
{
39 protected $serverPort;
41 protected $useWindowsAuth = false;
43 protected $lastInsertId = null;
45 protected $lastAffectedRowCount = null;
47 protected $subqueryId = 0;
49 protected $scrollableCursor = true;
51 protected $prepareStatements = true;
52 /** @var stdClass[][]|null */
53 protected $binaryColumnCache = null;
54 /** @var stdClass[][]|null */
55 protected $bitColumnCache = null;
57 protected $ignoreDupKeyErrors = false;
59 protected $ignoreErrors = [];
61 public function implicitGroupby() {
65 public function implicitOrderby() {
69 public function unionSupportsOrderAndLimit() {
73 public function __construct( array $params ) {
74 $this->serverPort
= $params['port'];
75 $this->useWindowsAuth
= $params['UseWindowsAuth'];
77 parent
::__construct( $params );
81 * Usually aborts on failure
82 * @param string $server
84 * @param string $password
85 * @param string $dbName
86 * @throws DBConnectionError
87 * @return bool|resource|null
89 public function open( $server, $user, $password, $dbName ) {
90 # Test for driver support, to avoid suppressed fatal error
91 if ( !function_exists( 'sqlsrv_connect' ) ) {
92 throw new DBConnectionError(
94 "Microsoft SQL Server Native (sqlsrv) functions missing.
95 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
99 # e.g. the class is being loaded
100 if ( !strlen( $user ) ) {
105 $this->server
= $server;
107 $this->password
= $password;
108 $this->dbName
= $dbName;
110 $connectionInfo = [];
113 $connectionInfo['Database'] = $dbName;
116 // Decide which auth scenerio to use
117 // if we are using Windows auth, then don't add credentials to $connectionInfo
118 if ( !$this->useWindowsAuth
) {
119 $connectionInfo['UID'] = $user;
120 $connectionInfo['PWD'] = $password;
123 Wikimedia\
suppressWarnings();
124 $this->conn
= sqlsrv_connect( $server, $connectionInfo );
125 Wikimedia\restoreWarnings
();
127 if ( $this->conn
=== false ) {
128 throw new DBConnectionError( $this, $this->lastError() );
131 $this->opened
= true;
137 * Closes a database connection, if it is open
138 * Returns success, true if already closed
141 protected function closeConnection() {
142 return sqlsrv_close( $this->conn
);
146 * @param bool|MssqlResultWrapper|resource $result
147 * @return bool|MssqlResultWrapper
149 protected function resultObject( $result ) {
152 } elseif ( $result instanceof MssqlResultWrapper
) {
154 } elseif ( $result === true ) {
155 // Successful write query
158 return new MssqlResultWrapper( $this, $result );
164 * @return bool|MssqlResultWrapper|resource
165 * @throws DBUnexpectedError
167 protected function doQuery( $sql ) {
168 // several extensions seem to think that all databases support limits
169 // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
170 // so to catch any of those extensions we'll do a quick check for a
171 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
172 // the LIMIT clause and passes the result to $this->limitResult();
173 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
174 // massage LIMIT -> TopN
175 $sql = $this->LimitToTopN( $sql );
178 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
179 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
180 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
181 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
186 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
187 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
188 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
189 // strings make php throw a fatal error "Severe error translating Unicode"
190 if ( $this->scrollableCursor
) {
191 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
196 if ( $this->prepareStatements
) {
197 // we do prepare + execute so we can get its field metadata for later usage if desired
198 $stmt = sqlsrv_prepare( $this->conn
, $sql, [], $scrollArr );
199 $success = sqlsrv_execute( $stmt );
201 $stmt = sqlsrv_query( $this->conn
, $sql, [], $scrollArr );
202 $success = (bool)$stmt;
205 // Make a copy to ensure what we add below does not get reflected in future queries
206 $ignoreErrors = $this->ignoreErrors
;
208 if ( $this->ignoreDupKeyErrors
) {
209 // ignore duplicate key errors
210 // this emulates INSERT IGNORE in MySQL
211 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
212 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
213 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
216 if ( $success === false ) {
217 $errors = sqlsrv_errors();
220 foreach ( $errors as $err ) {
221 if ( !in_array( $err['code'], $ignoreErrors ) ) {
227 if ( $success === false ) {
231 // remember number of rows affected
232 $this->lastAffectedRowCount
= sqlsrv_rows_affected( $stmt );
237 public function freeResult( $res ) {
238 if ( $res instanceof ResultWrapper
) {
242 sqlsrv_free_stmt( $res );
246 * @param MssqlResultWrapper $res
249 public function fetchObject( $res ) {
250 // $res is expected to be an instance of MssqlResultWrapper here
251 return $res->fetchObject();
255 * @param MssqlResultWrapper $res
258 public function fetchRow( $res ) {
259 return $res->fetchRow();
266 public function numRows( $res ) {
267 if ( $res instanceof ResultWrapper
) {
271 $ret = sqlsrv_num_rows( $res );
273 if ( $ret === false ) {
274 // we cannot get an amount of rows from this cursor type
275 // has_rows returns bool true/false if the result has rows
276 $ret = (int)sqlsrv_has_rows( $res );
286 public function numFields( $res ) {
287 if ( $res instanceof ResultWrapper
) {
291 return sqlsrv_num_fields( $res );
299 public function fieldName( $res, $n ) {
300 if ( $res instanceof ResultWrapper
) {
304 return sqlsrv_field_metadata( $res )[$n]['Name'];
308 * This must be called after nextSequenceVal
311 public function insertId() {
312 return $this->lastInsertId
;
316 * @param MssqlResultWrapper $res
320 public function dataSeek( $res, $row ) {
321 return $res->seek( $row );
327 public function lastError() {
329 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
330 if ( $retErrors != null ) {
331 foreach ( $retErrors as $arrError ) {
332 $strRet .= $this->formatError( $arrError ) . "\n";
335 $strRet = "No errors found";
345 private function formatError( $err ) {
346 return '[SQLSTATE ' .
347 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
353 public function lastErrno() {
354 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
355 if ( $err !== null && isset( $err[0] ) ) {
356 return $err[0]['code'];
365 protected function fetchAffectedRowCount() {
366 return $this->lastAffectedRowCount
;
372 * @param mixed $table Array or string, table name(s) (prefix auto-added)
373 * @param mixed $vars Array or string, field name(s) to be retrieved
374 * @param mixed $conds Array or string, condition(s) for WHERE
375 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
376 * @param array $options Associative array of options (e.g.
377 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
378 * code for list of supported stuff
379 * @param array $join_conds Associative array of table join conditions
380 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
381 * @return mixed Database result resource (feed to Database::fetchObject
382 * or whatever), or false on failure
383 * @throws DBQueryError
384 * @throws DBUnexpectedError
387 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
388 $options = [], $join_conds = []
390 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
391 if ( isset( $options['EXPLAIN'] ) ) {
393 $this->scrollableCursor
= false;
394 $this->prepareStatements
= false;
395 $this->query( "SET SHOWPLAN_ALL ON" );
396 $ret = $this->query( $sql, $fname );
397 $this->query( "SET SHOWPLAN_ALL OFF" );
398 } catch ( DBQueryError
$dqe ) {
399 if ( isset( $options['FOR COUNT'] ) ) {
400 // likely don't have privs for SHOWPLAN, so run a select count instead
401 $this->query( "SET SHOWPLAN_ALL OFF" );
402 unset( $options['EXPLAIN'] );
403 $ret = $this->select(
405 'COUNT(*) AS EstimateRows',
412 // someone actually wanted the query plan instead of an est row count
413 // let them know of the error
414 $this->scrollableCursor
= true;
415 $this->prepareStatements
= true;
419 $this->scrollableCursor
= true;
420 $this->prepareStatements
= true;
423 return $this->query( $sql, $fname );
429 * @param mixed $table Array or string, table name(s) (prefix auto-added)
430 * @param mixed $vars Array or string, field name(s) to be retrieved
431 * @param mixed $conds Array or string, condition(s) for WHERE
432 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
433 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
434 * see Database::makeSelectOptions code for list of supported stuff
435 * @param array $join_conds Associative array of table join conditions (optional)
436 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
437 * @return string The SQL text
439 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
440 $options = [], $join_conds = []
442 if ( isset( $options['EXPLAIN'] ) ) {
443 unset( $options['EXPLAIN'] );
446 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
448 // try to rewrite aggregations of bit columns (currently MAX and MIN)
449 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
451 if ( is_array( $table ) ) {
454 $t = array_pop( $tables );
455 if ( is_array( $t ) ) {
456 $tables = array_merge( $tables, $t );
458 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
462 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
465 foreach ( $bitColumns as $col => $info ) {
467 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
468 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
470 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
477 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
480 $this->scrollableCursor
= false;
482 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
483 } catch ( Exception
$e ) {
484 $this->scrollableCursor
= true;
487 $this->scrollableCursor
= true;
490 public function delete( $table, $conds, $fname = __METHOD__
) {
491 $this->scrollableCursor
= false;
493 parent
::delete( $table, $conds, $fname );
494 } catch ( Exception
$e ) {
495 $this->scrollableCursor
= true;
498 $this->scrollableCursor
= true;
502 * Estimate rows in dataset
503 * Returns estimated count, based on SHOWPLAN_ALL output
504 * This is not necessarily an accurate estimate, so use sparingly
505 * Returns -1 if count cannot be found
506 * Takes same arguments as Database::select()
507 * @param string $table
508 * @param string $vars
509 * @param string $conds
510 * @param string $fname
511 * @param array $options
512 * @param array $join_conds
515 public function estimateRowCount( $table, $vars = '*', $conds = '',
516 $fname = __METHOD__
, $options = [], $join_conds = []
518 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
519 $options['EXPLAIN'] = true;
520 $options['FOR COUNT'] = true;
521 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
525 $row = $this->fetchRow( $res );
527 if ( isset( $row['EstimateRows'] ) ) {
528 $rows = (int)$row['EstimateRows'];
536 * Returns information about an index
537 * If errors are explicitly ignored, returns NULL on failure
538 * @param string $table
539 * @param string $index
540 * @param string $fname
541 * @return array|bool|null
543 public function indexInfo( $table, $index, $fname = __METHOD__
) {
544 # This does not return the same info as MYSQL would, but that's OK
545 # because MediaWiki never uses the returned value except to check for
546 # the existence of indexes.
547 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
548 $res = $this->query( $sql, $fname );
555 foreach ( $res as $row ) {
556 if ( $row->index_name
== $index ) {
557 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
558 $cols = explode( ", ", $row->index_keys
);
559 foreach ( $cols as $col ) {
560 $row->Column_name
= trim( $col );
561 $result[] = clone $row;
563 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
564 $row->Non_unique
= 0;
565 $cols = explode( ", ", $row->index_keys
);
566 foreach ( $cols as $col ) {
567 $row->Column_name
= trim( $col );
568 $result[] = clone $row;
573 return $result ?
: false;
577 * INSERT wrapper, inserts an array into a table
579 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
582 * Usually aborts on failure
583 * If errors are explicitly ignored, returns success
584 * @param string $table
585 * @param array $arrToInsert
586 * @param string $fname
587 * @param array $options
591 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
592 # No rows to insert, easy just return now
593 if ( !count( $arrToInsert ) ) {
597 if ( !is_array( $options ) ) {
598 $options = [ $options ];
601 $table = $this->tableName( $table );
603 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
604 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
607 // We know the table we're inserting into, get its identity column
609 // strip matching square brackets and the db/schema from table name
610 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
611 $tableRaw = array_pop( $tableRawArr );
612 $res = $this->doQuery(
613 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
614 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
616 if ( $res && sqlsrv_has_rows( $res ) ) {
617 // There is an identity for this table.
618 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
619 $identity = array_pop( $identityArr );
621 sqlsrv_free_stmt( $res );
623 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
624 $binaryColumns = $this->getBinaryColumns( $table );
626 // INSERT IGNORE is not supported by SQL Server
627 // remove IGNORE from options list and set ignore flag to true
628 if ( in_array( 'IGNORE', $options ) ) {
629 $options = array_diff( $options, [ 'IGNORE' ] );
630 $this->ignoreDupKeyErrors
= true;
634 foreach ( $arrToInsert as $a ) {
635 // start out with empty identity column, this is so we can return
636 // it as a result of the INSERT logic
639 $identityClause = '';
641 // if we have an identity column
644 foreach ( $a as $k => $v ) {
645 if ( $k == $identity ) {
646 if ( !is_null( $v ) ) {
647 // there is a value being passed to us,
648 // we need to turn on and off inserted identity
649 $sqlPre = "SET IDENTITY_INSERT $table ON;";
650 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
652 // we can't insert NULL into an identity column,
653 // so remove the column from the insert.
659 // we want to output an identity column as result
660 $identityClause = "OUTPUT INSERTED.$identity ";
663 $keys = array_keys( $a );
665 // Build the actual query
666 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
667 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
670 foreach ( $a as $key => $value ) {
671 if ( isset( $binaryColumns[$key] ) ) {
672 $value = new MssqlBlob( $value );
679 if ( is_null( $value ) ) {
681 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
682 if ( is_object( $value ) && $value instanceof Blob
) {
683 $sql .= $this->addQuotes( $value );
685 $sql .= $this->addQuotes( serialize( $value ) );
688 $sql .= $this->addQuotes( $value );
691 $sql .= ')' . $sqlPost;
694 $this->scrollableCursor
= false;
696 $ret = $this->query( $sql );
697 } catch ( Exception
$e ) {
698 $this->scrollableCursor
= true;
699 $this->ignoreDupKeyErrors
= false;
702 $this->scrollableCursor
= true;
704 if ( $ret instanceof ResultWrapper
&& !is_null( $identity ) ) {
705 // Then we want to get the identity column value we were assigned and save it off
706 $row = $ret->fetchObject();
707 if ( is_object( $row ) ) {
708 $this->lastInsertId
= $row->$identity;
709 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
710 // used if we got an identity back, we know for sure a row was affected, so
712 if ( $this->lastAffectedRowCount
== -1 ) {
713 $this->lastAffectedRowCount
= 1;
719 $this->ignoreDupKeyErrors
= false;
725 * INSERT SELECT wrapper
726 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
727 * Source items may be literals rather than field names, but strings should
728 * be quoted with Database::addQuotes().
729 * @param string $destTable
730 * @param array|string $srcTable May be an array of tables.
731 * @param array $varMap
732 * @param array $conds May be "*" to copy the whole table.
733 * @param string $fname
734 * @param array $insertOptions
735 * @param array $selectOptions
736 * @param array $selectJoinConds
740 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
741 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
743 $this->scrollableCursor
= false;
745 $ret = parent
::nativeInsertSelect(
755 } catch ( Exception
$e ) {
756 $this->scrollableCursor
= true;
759 $this->scrollableCursor
= true;
765 * UPDATE wrapper. Takes a condition array and a SET array.
767 * @param string $table Name of the table to UPDATE. This will be passed through
768 * Database::tableName().
770 * @param array $values An array of values to SET. For each array element,
771 * the key gives the field name, and the value gives the data
772 * to set that field to. The data will be quoted by
773 * Database::addQuotes().
775 * @param array $conds An array of conditions (WHERE). See
776 * Database::select() for the details of the format of
777 * condition arrays. Use '*' to update all rows.
779 * @param string $fname The function name of the caller (from __METHOD__),
780 * for logging and profiling.
782 * @param array $options An array of UPDATE options, can be:
783 * - IGNORE: Ignore unique key conflicts
784 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
786 * @throws DBUnexpectedError
789 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
790 $table = $this->tableName( $table );
791 $binaryColumns = $this->getBinaryColumns( $table );
793 $opts = $this->makeUpdateOptions( $options );
794 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
796 if ( $conds !== [] && $conds !== '*' ) {
797 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
800 $this->scrollableCursor
= false;
802 $this->query( $sql );
803 } catch ( Exception
$e ) {
804 $this->scrollableCursor
= true;
807 $this->scrollableCursor
= true;
812 * Makes an encoded list of strings from an array
813 * @param array $a Containing the data
814 * @param int $mode Constant
815 * - LIST_COMMA: comma separated, no field names
816 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
817 * the documentation for $conds in Database::select().
818 * - LIST_OR: ORed WHERE clause (without the WHERE)
819 * - LIST_SET: comma separated with field names, like a SET clause
820 * - LIST_NAMES: comma separated field names
821 * @param array $binaryColumns Contains a list of column names that are binary types
822 * This is a custom parameter only present for MS SQL.
824 * @throws DBUnexpectedError
827 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
828 if ( !is_array( $a ) ) {
829 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
832 if ( $mode != LIST_NAMES
) {
833 // In MS SQL, values need to be specially encoded when they are
834 // inserted into binary fields. Perform this necessary encoding
835 // for the specified set of columns.
836 foreach ( array_keys( $a ) as $field ) {
837 if ( !isset( $binaryColumns[$field] ) ) {
841 if ( is_array( $a[$field] ) ) {
842 foreach ( $a[$field] as &$v ) {
843 $v = new MssqlBlob( $v );
847 $a[$field] = new MssqlBlob( $a[$field] );
852 return parent
::makeList( $a, $mode );
856 * @param string $table
857 * @param string $field
858 * @return int Returns the size of a text field, or -1 for "unlimited"
860 public function textFieldSize( $table, $field ) {
861 $table = $this->tableName( $table );
862 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
863 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
864 $res = $this->query( $sql );
865 $row = $this->fetchRow( $res );
867 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
868 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
875 * Construct a LIMIT query with optional offset
876 * This is used for query pages
878 * @param string $sql SQL query we will append the limit too
879 * @param int $limit The SQL limit
880 * @param bool|int $offset The SQL offset (default false)
881 * @return array|string
882 * @throws DBUnexpectedError
884 public function limitResult( $sql, $limit, $offset = false ) {
885 if ( $offset === false ||
$offset == 0 ) {
886 if ( strpos( $sql, "SELECT" ) === false ) {
887 return "TOP {$limit} " . $sql;
889 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
890 'SELECT$1 TOP ' . $limit, $sql, 1 );
893 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
894 $select = $orderby = [];
895 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
896 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
898 $first = $offset +
1;
899 $last = $offset +
$limit;
900 $sub1 = 'sub_' . $this->subqueryId
;
901 $sub2 = 'sub_' . ( $this->subqueryId +
1 );
902 $this->subqueryId +
= 2;
905 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
909 $overOrder = 'ORDER BY (SELECT 1)';
911 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
912 // don't need to strip it out if we're using a FOR XML clause
913 $sql = str_replace( $orderby[1], '', $sql );
915 $overOrder = $orderby[1];
916 $postOrder = ' ' . $overOrder;
918 $sql = "SELECT {$select[1]}
920 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
921 FROM ({$sql}) {$sub1}
923 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
930 * If there is a limit clause, parse it, strip it, and pass the remaining
931 * SQL through limitResult() with the appropriate parameters. Not the
932 * prettiest solution, but better than building a whole new parser. This
933 * exists becase there are still too many extensions that don't use dynamic
937 * @return array|mixed|string
939 public function LimitToTopN( $sql ) {
940 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
941 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
942 if ( preg_match( $pattern, $sql, $matches ) ) {
943 $row_count = $matches[4];
944 $offset = $matches[3] ?
: $matches[6] ?
: false;
946 // strip the matching LIMIT clause out
947 $sql = str_replace( $matches[0], '', $sql );
949 return $this->limitResult( $sql, $row_count, $offset );
956 * @return string Wikitext of a link to the server software's web site
958 public function getSoftwareLink() {
959 return "[{{int:version-db-mssql-url}} MS SQL Server]";
963 * @return string Version information from the database
965 public function getServerVersion() {
966 $server_info = sqlsrv_server_info( $this->conn
);
968 if ( isset( $server_info['SQLServerVersion'] ) ) {
969 $version = $server_info['SQLServerVersion'];
976 * @param string $table
977 * @param string $fname
980 public function tableExists( $table, $fname = __METHOD__
) {
981 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
983 if ( $db !== false ) {
985 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
989 if ( $schema === false ) {
990 $schema = $this->schema
;
993 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
994 WHERE TABLE_TYPE = 'BASE TABLE'
995 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
997 if ( $res->numRows() ) {
1005 * Query whether a given column exists in the mediawiki schema
1006 * @param string $table
1007 * @param string $field
1008 * @param string $fname
1011 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1012 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1014 if ( $db !== false ) {
1016 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1020 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1021 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1023 if ( $res->numRows() ) {
1030 public function fieldInfo( $table, $field ) {
1031 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1033 if ( $db !== false ) {
1035 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1039 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1040 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1042 $meta = $res->fetchRow();
1044 return new MssqlField( $meta );
1051 * Begin a transaction, committing any previously open transaction
1052 * @param string $fname
1054 protected function doBegin( $fname = __METHOD__
) {
1055 sqlsrv_begin_transaction( $this->conn
);
1056 $this->trxLevel
= 1;
1061 * @param string $fname
1063 protected function doCommit( $fname = __METHOD__
) {
1064 sqlsrv_commit( $this->conn
);
1065 $this->trxLevel
= 0;
1069 * Rollback a transaction.
1070 * No-op on non-transactional databases.
1071 * @param string $fname
1073 protected function doRollback( $fname = __METHOD__
) {
1074 sqlsrv_rollback( $this->conn
);
1075 $this->trxLevel
= 0;
1082 public function strencode( $s ) {
1083 // Should not be called by us
1084 return str_replace( "'", "''", $s );
1088 * @param string|int|null|bool|Blob $s
1089 * @return string|int
1091 public function addQuotes( $s ) {
1092 if ( $s instanceof MssqlBlob
) {
1094 } elseif ( $s instanceof Blob
) {
1095 // this shouldn't really ever be called, but it's here if needed
1096 // (and will quite possibly make the SQL error out)
1097 $blob = new MssqlBlob( $s->fetch() );
1098 return $blob->fetch();
1100 if ( is_bool( $s ) ) {
1103 return parent
::addQuotes( $s );
1111 public function addIdentifierQuotes( $s ) {
1112 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1113 return '[' . $s . ']';
1117 * @param string $name
1120 public function isQuotedIdentifier( $name ) {
1121 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1125 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1128 * @param string $escapeChar
1131 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1132 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1133 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1134 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1142 public function selectDB( $db ) {
1144 $this->dbName
= $db;
1145 $this->query( "USE $db" );
1147 } catch ( Exception
$e ) {
1153 * @param array $options An associative array of options to be turned into
1154 * an SQL query, valid keys are listed in the function.
1157 public function makeSelectOptions( $options ) {
1162 foreach ( $options as $key => $option ) {
1163 if ( is_numeric( $key ) ) {
1164 $noKeyOptions[$option] = true;
1168 $tailOpts .= $this->makeGroupByWithHaving( $options );
1170 $tailOpts .= $this->makeOrderBy( $options );
1172 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1173 $startOpts .= 'DISTINCT';
1176 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1177 // used in group concat field emulation
1178 $tailOpts .= " FOR XML PATH('')";
1181 // we want this to be compatible with the output of parent::makeSelectOptions()
1182 return [ $startOpts, '', $tailOpts, '', '' ];
1185 public function getType() {
1190 * @param array $stringList
1193 public function buildConcat( $stringList ) {
1194 return implode( ' + ', $stringList );
1198 * Build a GROUP_CONCAT or equivalent statement for a query.
1199 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1201 * This is useful for combining a field for several rows into a single string.
1202 * NULL values will not appear in the output, duplicated values will appear,
1203 * and the resulting delimiter-separated values have no defined sort order.
1204 * Code using the results may need to use the PHP unique() or sort() methods.
1206 * @param string $delim Glue to bind the results together
1207 * @param string|array $table Table name
1208 * @param string $field Field name
1209 * @param string|array $conds Conditions
1210 * @param string|array $join_conds Join conditions
1211 * @return string SQL text
1214 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1217 $gcsq = 'gcsq_' . $this->subqueryId
;
1218 $this->subqueryId++
;
1220 $delimLen = strlen( $delim );
1221 $fld = "{$field} + {$this->addQuotes( $delim )}";
1222 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1223 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1224 . ") {$gcsq} ({$field}))";
1229 public function buildSubstring( $input, $startPosition, $length = null ) {
1230 $this->assertBuildSubstringParams( $startPosition, $length );
1231 if ( $length === null ) {
1233 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1234 * length returned use the default maximum size of text.
1235 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1237 $length = 2147483647;
1239 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1243 * Returns an associative array for fields that are of type varbinary, binary, or image
1244 * $table can be either a raw table name or passed through tableName() first
1245 * @param string $table
1248 private function getBinaryColumns( $table ) {
1249 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1250 $tableRaw = array_pop( $tableRawArr );
1252 if ( $this->binaryColumnCache
=== null ) {
1253 $this->populateColumnCaches();
1256 return isset( $this->binaryColumnCache
[$tableRaw] )
1257 ?
$this->binaryColumnCache
[$tableRaw]
1262 * @param string $table
1265 private function getBitColumns( $table ) {
1266 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1267 $tableRaw = array_pop( $tableRawArr );
1269 if ( $this->bitColumnCache
=== null ) {
1270 $this->populateColumnCaches();
1273 return isset( $this->bitColumnCache
[$tableRaw] )
1274 ?
$this->bitColumnCache
[$tableRaw]
1278 private function populateColumnCaches() {
1279 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1281 'TABLE_CATALOG' => $this->dbName
,
1282 'TABLE_SCHEMA' => $this->schema
,
1283 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1286 $this->binaryColumnCache
= [];
1287 $this->bitColumnCache
= [];
1288 foreach ( $res as $row ) {
1289 if ( $row->DATA_TYPE
== 'bit' ) {
1290 $this->bitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1292 $this->binaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1298 * @param string $name
1299 * @param string $format
1302 function tableName( $name, $format = 'quoted' ) {
1303 # Replace reserved words with better ones
1306 return $this->realTableName( 'mwuser', $format );
1308 return $this->realTableName( $name, $format );
1313 * call this instead of tableName() in the updater when renaming tables
1314 * @param string $name
1315 * @param string $format One of quoted, raw, or split
1318 function realTableName( $name, $format = 'quoted' ) {
1319 $table = parent
::tableName( $name, $format );
1320 if ( $format == 'split' ) {
1321 // Used internally, we want the schema split off from the table name and returned
1322 // as a list with 3 elements (database, schema, table)
1323 $table = explode( '.', $table );
1324 while ( count( $table ) < 3 ) {
1325 array_unshift( $table, false );
1333 * @param string $tableName
1334 * @param string $fName
1335 * @return bool|ResultWrapper
1338 public function dropTable( $tableName, $fName = __METHOD__
) {
1339 if ( !$this->tableExists( $tableName, $fName ) ) {
1343 // parent function incorrectly appends CASCADE, which we don't want
1344 $sql = "DROP TABLE " . $this->tableName( $tableName );
1346 return $this->query( $sql, $fName );
1350 * Called in the installer and updater.
1351 * Probably doesn't need to be called anywhere else in the codebase.
1352 * @param bool|null $value
1355 public function prepareStatements( $value = null ) {
1356 $old = $this->prepareStatements
;
1357 if ( $value !== null ) {
1358 $this->prepareStatements
= $value;
1365 * Called in the installer and updater.
1366 * Probably doesn't need to be called anywhere else in the codebase.
1367 * @param bool|null $value
1370 public function scrollableCursor( $value = null ) {
1371 $old = $this->scrollableCursor
;
1372 if ( $value !== null ) {
1373 $this->scrollableCursor
= $value;
1380 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );