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 $mUseWindowsAuth = false;
41 protected $mInsertId = null;
42 protected $mLastResult = null;
43 protected $mAffectedRows = null;
44 protected $mSubqueryId = 0;
45 protected $mScrollableCursor = true;
46 protected $mPrepareStatements = true;
47 protected $mBinaryColumnCache = null;
48 protected $mBitColumnCache = null;
49 protected $mIgnoreDupKeyErrors = false;
50 protected $mIgnoreErrors = [];
52 public function implicitGroupby() {
56 public function implicitOrderby() {
60 public function unionSupportsOrderAndLimit() {
64 public function __construct( array $params ) {
65 $this->mPort
= $params['port'];
66 $this->mUseWindowsAuth
= $params['UseWindowsAuth'];
68 parent
::__construct( $params );
72 * Usually aborts on failure
73 * @param string $server
75 * @param string $password
76 * @param string $dbName
77 * @throws DBConnectionError
78 * @return bool|resource|null
80 public function open( $server, $user, $password, $dbName ) {
81 # Test for driver support, to avoid suppressed fatal error
82 if ( !function_exists( 'sqlsrv_connect' ) ) {
83 throw new DBConnectionError(
85 "Microsoft SQL Server Native (sqlsrv) functions missing.
86 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
90 # e.g. the class is being loaded
91 if ( !strlen( $user ) ) {
96 $this->mServer
= $server;
98 $this->mPassword
= $password;
99 $this->mDBname
= $dbName;
101 $connectionInfo = [];
104 $connectionInfo['Database'] = $dbName;
107 // Decide which auth scenerio to use
108 // if we are using Windows auth, then don't add credentials to $connectionInfo
109 if ( !$this->mUseWindowsAuth
) {
110 $connectionInfo['UID'] = $user;
111 $connectionInfo['PWD'] = $password;
114 MediaWiki\
suppressWarnings();
115 $this->mConn
= sqlsrv_connect( $server, $connectionInfo );
116 MediaWiki\restoreWarnings
();
118 if ( $this->mConn
=== false ) {
119 throw new DBConnectionError( $this, $this->lastError() );
122 $this->mOpened
= true;
128 * Closes a database connection, if it is open
129 * Returns success, true if already closed
132 protected function closeConnection() {
133 return sqlsrv_close( $this->mConn
);
137 * @param bool|MssqlResultWrapper|resource $result
138 * @return bool|MssqlResultWrapper
140 protected function resultObject( $result ) {
143 } elseif ( $result instanceof MssqlResultWrapper
) {
145 } elseif ( $result === true ) {
146 // Successful write query
149 return new MssqlResultWrapper( $this, $result );
155 * @return bool|MssqlResultWrapper|resource
156 * @throws DBUnexpectedError
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->mScrollableCursor
) {
182 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
187 if ( $this->mPrepareStatements
) {
188 // we do prepare + execute so we can get its field metadata for later usage if desired
189 $stmt = sqlsrv_prepare( $this->mConn
, $sql, [], $scrollArr );
190 $success = sqlsrv_execute( $stmt );
192 $stmt = sqlsrv_query( $this->mConn
, $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->mIgnoreErrors
;
199 if ( $this->mIgnoreDupKeyErrors
) {
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->mAffectedRows
= sqlsrv_rows_affected( $stmt );
228 public function freeResult( $res ) {
229 if ( $res instanceof ResultWrapper
) {
233 sqlsrv_free_stmt( $res );
237 * @param MssqlResultWrapper $res
240 public function fetchObject( $res ) {
241 // $res is expected to be an instance of MssqlResultWrapper here
242 return $res->fetchObject();
246 * @param MssqlResultWrapper $res
249 public function fetchRow( $res ) {
250 return $res->fetchRow();
257 public function numRows( $res ) {
258 if ( $res instanceof ResultWrapper
) {
262 $ret = sqlsrv_num_rows( $res );
264 if ( $ret === false ) {
265 // we cannot get an amount of rows from this cursor type
266 // has_rows returns bool true/false if the result has rows
267 $ret = (int)sqlsrv_has_rows( $res );
277 public function numFields( $res ) {
278 if ( $res instanceof ResultWrapper
) {
282 return sqlsrv_num_fields( $res );
290 public function fieldName( $res, $n ) {
291 if ( $res instanceof ResultWrapper
) {
295 return sqlsrv_field_metadata( $res )[$n]['Name'];
299 * This must be called after nextSequenceVal
302 public function insertId() {
303 return $this->mInsertId
;
307 * @param MssqlResultWrapper $res
311 public function dataSeek( $res, $row ) {
312 return $res->seek( $row );
318 public function lastError() {
320 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
321 if ( $retErrors != null ) {
322 foreach ( $retErrors as $arrError ) {
323 $strRet .= $this->formatError( $arrError ) . "\n";
326 $strRet = "No errors found";
336 private function formatError( $err ) {
337 return '[SQLSTATE ' .
338 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
344 public function lastErrno() {
345 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
346 if ( $err !== null && isset( $err[0] ) ) {
347 return $err[0]['code'];
356 public function affectedRows() {
357 return $this->mAffectedRows
;
363 * @param mixed $table Array or string, table name(s) (prefix auto-added)
364 * @param mixed $vars Array or string, field name(s) to be retrieved
365 * @param mixed $conds Array or string, condition(s) for WHERE
366 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
367 * @param array $options Associative array of options (e.g.
368 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
369 * code for list of supported stuff
370 * @param array $join_conds Associative array of table join conditions
371 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
372 * @return mixed Database result resource (feed to Database::fetchObject
373 * or whatever), or false on failure
374 * @throws DBQueryError
375 * @throws DBUnexpectedError
378 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
379 $options = [], $join_conds = []
381 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
382 if ( isset( $options['EXPLAIN'] ) ) {
384 $this->mScrollableCursor
= false;
385 $this->mPrepareStatements
= false;
386 $this->query( "SET SHOWPLAN_ALL ON" );
387 $ret = $this->query( $sql, $fname );
388 $this->query( "SET SHOWPLAN_ALL OFF" );
389 } catch ( DBQueryError
$dqe ) {
390 if ( isset( $options['FOR COUNT'] ) ) {
391 // likely don't have privs for SHOWPLAN, so run a select count instead
392 $this->query( "SET SHOWPLAN_ALL OFF" );
393 unset( $options['EXPLAIN'] );
394 $ret = $this->select(
396 'COUNT(*) AS EstimateRows',
403 // someone actually wanted the query plan instead of an est row count
404 // let them know of the error
405 $this->mScrollableCursor
= true;
406 $this->mPrepareStatements
= true;
410 $this->mScrollableCursor
= true;
411 $this->mPrepareStatements
= true;
414 return $this->query( $sql, $fname );
420 * @param mixed $table Array or string, table name(s) (prefix auto-added)
421 * @param mixed $vars Array or string, field name(s) to be retrieved
422 * @param mixed $conds Array or string, condition(s) for WHERE
423 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
424 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
425 * see Database::makeSelectOptions code for list of supported stuff
426 * @param array $join_conds Associative array of table join conditions (optional)
427 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
428 * @return string The SQL text
430 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
431 $options = [], $join_conds = []
433 if ( isset( $options['EXPLAIN'] ) ) {
434 unset( $options['EXPLAIN'] );
437 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
439 // try to rewrite aggregations of bit columns (currently MAX and MIN)
440 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
442 if ( is_array( $table ) ) {
443 foreach ( $table as $t ) {
444 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
447 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
450 foreach ( $bitColumns as $col => $info ) {
452 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
453 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
455 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
462 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
465 $this->mScrollableCursor
= false;
467 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
468 } catch ( Exception
$e ) {
469 $this->mScrollableCursor
= true;
472 $this->mScrollableCursor
= true;
475 public function delete( $table, $conds, $fname = __METHOD__
) {
476 $this->mScrollableCursor
= false;
478 parent
::delete( $table, $conds, $fname );
479 } catch ( Exception
$e ) {
480 $this->mScrollableCursor
= true;
483 $this->mScrollableCursor
= true;
487 * Estimate rows in dataset
488 * Returns estimated count, based on SHOWPLAN_ALL output
489 * This is not necessarily an accurate estimate, so use sparingly
490 * Returns -1 if count cannot be found
491 * Takes same arguments as Database::select()
492 * @param string $table
493 * @param string $vars
494 * @param string $conds
495 * @param string $fname
496 * @param array $options
499 public function estimateRowCount( $table, $vars = '*', $conds = '',
500 $fname = __METHOD__
, $options = []
502 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
503 $options['EXPLAIN'] = true;
504 $options['FOR COUNT'] = true;
505 $res = $this->select( $table, $vars, $conds, $fname, $options );
509 $row = $this->fetchRow( $res );
511 if ( isset( $row['EstimateRows'] ) ) {
512 $rows = (int)$row['EstimateRows'];
520 * Returns information about an index
521 * If errors are explicitly ignored, returns NULL on failure
522 * @param string $table
523 * @param string $index
524 * @param string $fname
525 * @return array|bool|null
527 public function indexInfo( $table, $index, $fname = __METHOD__
) {
528 # This does not return the same info as MYSQL would, but that's OK
529 # because MediaWiki never uses the returned value except to check for
530 # the existence of indexes.
531 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
532 $res = $this->query( $sql, $fname );
539 foreach ( $res as $row ) {
540 if ( $row->index_name
== $index ) {
541 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
542 $cols = explode( ", ", $row->index_keys
);
543 foreach ( $cols as $col ) {
544 $row->Column_name
= trim( $col );
545 $result[] = clone $row;
547 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
548 $row->Non_unique
= 0;
549 $cols = explode( ", ", $row->index_keys
);
550 foreach ( $cols as $col ) {
551 $row->Column_name
= trim( $col );
552 $result[] = clone $row;
557 return empty( $result ) ?
false : $result;
561 * INSERT wrapper, inserts an array into a table
563 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
566 * Usually aborts on failure
567 * If errors are explicitly ignored, returns success
568 * @param string $table
569 * @param array $arrToInsert
570 * @param string $fname
571 * @param array $options
575 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
576 # No rows to insert, easy just return now
577 if ( !count( $arrToInsert ) ) {
581 if ( !is_array( $options ) ) {
582 $options = [ $options ];
585 $table = $this->tableName( $table );
587 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
588 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
591 // We know the table we're inserting into, get its identity column
593 // strip matching square brackets and the db/schema from table name
594 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
595 $tableRaw = array_pop( $tableRawArr );
596 $res = $this->doQuery(
597 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
598 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
600 if ( $res && sqlsrv_has_rows( $res ) ) {
601 // There is an identity for this table.
602 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
603 $identity = array_pop( $identityArr );
605 sqlsrv_free_stmt( $res );
607 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
608 $binaryColumns = $this->getBinaryColumns( $table );
610 // INSERT IGNORE is not supported by SQL Server
611 // remove IGNORE from options list and set ignore flag to true
612 if ( in_array( 'IGNORE', $options ) ) {
613 $options = array_diff( $options, [ 'IGNORE' ] );
614 $this->mIgnoreDupKeyErrors
= true;
618 foreach ( $arrToInsert as $a ) {
619 // start out with empty identity column, this is so we can return
620 // it as a result of the INSERT logic
623 $identityClause = '';
625 // if we have an identity column
628 foreach ( $a as $k => $v ) {
629 if ( $k == $identity ) {
630 if ( !is_null( $v ) ) {
631 // there is a value being passed to us,
632 // we need to turn on and off inserted identity
633 $sqlPre = "SET IDENTITY_INSERT $table ON;";
634 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
636 // we can't insert NULL into an identity column,
637 // so remove the column from the insert.
643 // we want to output an identity column as result
644 $identityClause = "OUTPUT INSERTED.$identity ";
647 $keys = array_keys( $a );
649 // Build the actual query
650 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
651 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
654 foreach ( $a as $key => $value ) {
655 if ( isset( $binaryColumns[$key] ) ) {
656 $value = new MssqlBlob( $value );
663 if ( is_null( $value ) ) {
665 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
666 if ( is_object( $value ) && $value instanceof Blob
) {
667 $sql .= $this->addQuotes( $value );
669 $sql .= $this->addQuotes( serialize( $value ) );
672 $sql .= $this->addQuotes( $value );
675 $sql .= ')' . $sqlPost;
678 $this->mScrollableCursor
= false;
680 $ret = $this->query( $sql );
681 } catch ( Exception
$e ) {
682 $this->mScrollableCursor
= true;
683 $this->mIgnoreDupKeyErrors
= false;
686 $this->mScrollableCursor
= true;
688 if ( $ret instanceof ResultWrapper
&& !is_null( $identity ) ) {
689 // Then we want to get the identity column value we were assigned and save it off
690 $row = $ret->fetchObject();
691 if ( is_object( $row ) ) {
692 $this->mInsertId
= $row->$identity;
693 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
694 // used if we got an identity back, we know for sure a row was affected, so
696 if ( $this->mAffectedRows
== -1 ) {
697 $this->mAffectedRows
= 1;
703 $this->mIgnoreDupKeyErrors
= false;
709 * INSERT SELECT wrapper
710 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
711 * Source items may be literals rather than field names, but strings should
712 * be quoted with Database::addQuotes().
713 * @param string $destTable
714 * @param array|string $srcTable May be an array of tables.
715 * @param array $varMap
716 * @param array $conds May be "*" to copy the whole table.
717 * @param string $fname
718 * @param array $insertOptions
719 * @param array $selectOptions
720 * @return null|ResultWrapper
723 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
724 $insertOptions = [], $selectOptions = []
726 $this->mScrollableCursor
= false;
728 $ret = parent
::nativeInsertSelect(
737 } catch ( Exception
$e ) {
738 $this->mScrollableCursor
= true;
741 $this->mScrollableCursor
= true;
747 * UPDATE wrapper. Takes a condition array and a SET array.
749 * @param string $table Name of the table to UPDATE. This will be passed through
750 * Database::tableName().
752 * @param array $values An array of values to SET. For each array element,
753 * the key gives the field name, and the value gives the data
754 * to set that field to. The data will be quoted by
755 * Database::addQuotes().
757 * @param array $conds An array of conditions (WHERE). See
758 * Database::select() for the details of the format of
759 * condition arrays. Use '*' to update all rows.
761 * @param string $fname The function name of the caller (from __METHOD__),
762 * for logging and profiling.
764 * @param array $options An array of UPDATE options, can be:
765 * - IGNORE: Ignore unique key conflicts
766 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
768 * @throws DBUnexpectedError
771 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
772 $table = $this->tableName( $table );
773 $binaryColumns = $this->getBinaryColumns( $table );
775 $opts = $this->makeUpdateOptions( $options );
776 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
778 if ( $conds !== [] && $conds !== '*' ) {
779 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
782 $this->mScrollableCursor
= false;
784 $this->query( $sql );
785 } catch ( Exception
$e ) {
786 $this->mScrollableCursor
= true;
789 $this->mScrollableCursor
= true;
794 * Makes an encoded list of strings from an array
795 * @param array $a Containing the data
796 * @param int $mode Constant
797 * - LIST_COMMA: comma separated, no field names
798 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
799 * the documentation for $conds in Database::select().
800 * - LIST_OR: ORed WHERE clause (without the WHERE)
801 * - LIST_SET: comma separated with field names, like a SET clause
802 * - LIST_NAMES: comma separated field names
803 * @param array $binaryColumns Contains a list of column names that are binary types
804 * This is a custom parameter only present for MS SQL.
806 * @throws DBUnexpectedError
809 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
810 if ( !is_array( $a ) ) {
811 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
814 if ( $mode != LIST_NAMES
) {
815 // In MS SQL, values need to be specially encoded when they are
816 // inserted into binary fields. Perform this necessary encoding
817 // for the specified set of columns.
818 foreach ( array_keys( $a ) as $field ) {
819 if ( !isset( $binaryColumns[$field] ) ) {
823 if ( is_array( $a[$field] ) ) {
824 foreach ( $a[$field] as &$v ) {
825 $v = new MssqlBlob( $v );
829 $a[$field] = new MssqlBlob( $a[$field] );
834 return parent
::makeList( $a, $mode );
838 * @param string $table
839 * @param string $field
840 * @return int Returns the size of a text field, or -1 for "unlimited"
842 public function textFieldSize( $table, $field ) {
843 $table = $this->tableName( $table );
844 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
845 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
846 $res = $this->query( $sql );
847 $row = $this->fetchRow( $res );
849 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
850 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
857 * Construct a LIMIT query with optional offset
858 * This is used for query pages
860 * @param string $sql SQL query we will append the limit too
861 * @param int $limit The SQL limit
862 * @param bool|int $offset The SQL offset (default false)
863 * @return array|string
864 * @throws DBUnexpectedError
866 public function limitResult( $sql, $limit, $offset = false ) {
867 if ( $offset === false ||
$offset == 0 ) {
868 if ( strpos( $sql, "SELECT" ) === false ) {
869 return "TOP {$limit} " . $sql;
871 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
872 'SELECT$1 TOP ' . $limit, $sql, 1 );
875 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
876 $select = $orderby = [];
877 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
878 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
880 $first = $offset +
1;
881 $last = $offset +
$limit;
882 $sub1 = 'sub_' . $this->mSubqueryId
;
883 $sub2 = 'sub_' . ( $this->mSubqueryId +
1 );
884 $this->mSubqueryId +
= 2;
887 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
891 $overOrder = 'ORDER BY (SELECT 1)';
893 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
894 // don't need to strip it out if we're using a FOR XML clause
895 $sql = str_replace( $orderby[1], '', $sql );
897 $overOrder = $orderby[1];
898 $postOrder = ' ' . $overOrder;
900 $sql = "SELECT {$select[1]}
902 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
903 FROM ({$sql}) {$sub1}
905 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
912 * If there is a limit clause, parse it, strip it, and pass the remaining
913 * SQL through limitResult() with the appropriate parameters. Not the
914 * prettiest solution, but better than building a whole new parser. This
915 * exists becase there are still too many extensions that don't use dynamic
919 * @return array|mixed|string
921 public function LimitToTopN( $sql ) {
922 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
923 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
924 if ( preg_match( $pattern, $sql, $matches ) ) {
925 $row_count = $matches[4];
926 $offset = $matches[3] ?
: $matches[6] ?
: false;
928 // strip the matching LIMIT clause out
929 $sql = str_replace( $matches[0], '', $sql );
931 return $this->limitResult( $sql, $row_count, $offset );
938 * @return string Wikitext of a link to the server software's web site
940 public function getSoftwareLink() {
941 return "[{{int:version-db-mssql-url}} MS SQL Server]";
945 * @return string Version information from the database
947 public function getServerVersion() {
948 $server_info = sqlsrv_server_info( $this->mConn
);
950 if ( isset( $server_info['SQLServerVersion'] ) ) {
951 $version = $server_info['SQLServerVersion'];
958 * @param string $table
959 * @param string $fname
962 public function tableExists( $table, $fname = __METHOD__
) {
963 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
965 if ( $db !== false ) {
967 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
971 if ( $schema === false ) {
972 $schema = $this->mSchema
;
975 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
976 WHERE TABLE_TYPE = 'BASE TABLE'
977 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
979 if ( $res->numRows() ) {
987 * Query whether a given column exists in the mediawiki schema
988 * @param string $table
989 * @param string $field
990 * @param string $fname
993 public function fieldExists( $table, $field, $fname = __METHOD__
) {
994 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
996 if ( $db !== false ) {
998 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1002 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1003 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1005 if ( $res->numRows() ) {
1012 public function fieldInfo( $table, $field ) {
1013 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1015 if ( $db !== false ) {
1017 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1021 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1022 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1024 $meta = $res->fetchRow();
1026 return new MssqlField( $meta );
1033 * Begin a transaction, committing any previously open transaction
1034 * @param string $fname
1036 protected function doBegin( $fname = __METHOD__
) {
1037 sqlsrv_begin_transaction( $this->mConn
);
1038 $this->mTrxLevel
= 1;
1043 * @param string $fname
1045 protected function doCommit( $fname = __METHOD__
) {
1046 sqlsrv_commit( $this->mConn
);
1047 $this->mTrxLevel
= 0;
1051 * Rollback a transaction.
1052 * No-op on non-transactional databases.
1053 * @param string $fname
1055 protected function doRollback( $fname = __METHOD__
) {
1056 sqlsrv_rollback( $this->mConn
);
1057 $this->mTrxLevel
= 0;
1064 public function strencode( $s ) {
1065 // Should not be called by us
1067 return str_replace( "'", "''", $s );
1071 * @param string|int|null|bool|Blob $s
1072 * @return string|int
1074 public function addQuotes( $s ) {
1075 if ( $s instanceof MssqlBlob
) {
1077 } elseif ( $s instanceof Blob
) {
1078 // this shouldn't really ever be called, but it's here if needed
1079 // (and will quite possibly make the SQL error out)
1080 $blob = new MssqlBlob( $s->fetch() );
1081 return $blob->fetch();
1083 if ( is_bool( $s ) ) {
1086 return parent
::addQuotes( $s );
1094 public function addIdentifierQuotes( $s ) {
1095 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1096 return '[' . $s . ']';
1100 * @param string $name
1103 public function isQuotedIdentifier( $name ) {
1104 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1108 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1113 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1114 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1115 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1116 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1124 public function selectDB( $db ) {
1126 $this->mDBname
= $db;
1127 $this->query( "USE $db" );
1129 } catch ( Exception
$e ) {
1135 * @param array $options An associative array of options to be turned into
1136 * an SQL query, valid keys are listed in the function.
1139 public function makeSelectOptions( $options ) {
1144 foreach ( $options as $key => $option ) {
1145 if ( is_numeric( $key ) ) {
1146 $noKeyOptions[$option] = true;
1150 $tailOpts .= $this->makeGroupByWithHaving( $options );
1152 $tailOpts .= $this->makeOrderBy( $options );
1154 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1155 $startOpts .= 'DISTINCT';
1158 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1159 // used in group concat field emulation
1160 $tailOpts .= " FOR XML PATH('')";
1163 // we want this to be compatible with the output of parent::makeSelectOptions()
1164 return [ $startOpts, '', $tailOpts, '', '' ];
1167 public function getType() {
1172 * @param array $stringList
1175 public function buildConcat( $stringList ) {
1176 return implode( ' + ', $stringList );
1180 * Build a GROUP_CONCAT or equivalent statement for a query.
1181 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1183 * This is useful for combining a field for several rows into a single string.
1184 * NULL values will not appear in the output, duplicated values will appear,
1185 * and the resulting delimiter-separated values have no defined sort order.
1186 * Code using the results may need to use the PHP unique() or sort() methods.
1188 * @param string $delim Glue to bind the results together
1189 * @param string|array $table Table name
1190 * @param string $field Field name
1191 * @param string|array $conds Conditions
1192 * @param string|array $join_conds Join conditions
1193 * @return string SQL text
1196 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1199 $gcsq = 'gcsq_' . $this->mSubqueryId
;
1200 $this->mSubqueryId++
;
1202 $delimLen = strlen( $delim );
1203 $fld = "{$field} + {$this->addQuotes( $delim )}";
1204 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1205 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1206 . ") {$gcsq} ({$field}))";
1212 * Returns an associative array for fields that are of type varbinary, binary, or image
1213 * $table can be either a raw table name or passed through tableName() first
1214 * @param string $table
1217 private function getBinaryColumns( $table ) {
1218 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1219 $tableRaw = array_pop( $tableRawArr );
1221 if ( $this->mBinaryColumnCache
=== null ) {
1222 $this->populateColumnCaches();
1225 return isset( $this->mBinaryColumnCache
[$tableRaw] )
1226 ?
$this->mBinaryColumnCache
[$tableRaw]
1231 * @param string $table
1234 private function getBitColumns( $table ) {
1235 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1236 $tableRaw = array_pop( $tableRawArr );
1238 if ( $this->mBitColumnCache
=== null ) {
1239 $this->populateColumnCaches();
1242 return isset( $this->mBitColumnCache
[$tableRaw] )
1243 ?
$this->mBitColumnCache
[$tableRaw]
1247 private function populateColumnCaches() {
1248 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1250 'TABLE_CATALOG' => $this->mDBname
,
1251 'TABLE_SCHEMA' => $this->mSchema
,
1252 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1255 $this->mBinaryColumnCache
= [];
1256 $this->mBitColumnCache
= [];
1257 foreach ( $res as $row ) {
1258 if ( $row->DATA_TYPE
== 'bit' ) {
1259 $this->mBitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1261 $this->mBinaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1267 * @param string $name
1268 * @param string $format
1271 function tableName( $name, $format = 'quoted' ) {
1272 # Replace reserved words with better ones
1275 return $this->realTableName( 'mwuser', $format );
1277 return $this->realTableName( $name, $format );
1282 * call this instead of tableName() in the updater when renaming tables
1283 * @param string $name
1284 * @param string $format One of quoted, raw, or split
1287 function realTableName( $name, $format = 'quoted' ) {
1288 $table = parent
::tableName( $name, $format );
1289 if ( $format == 'split' ) {
1290 // Used internally, we want the schema split off from the table name and returned
1291 // as a list with 3 elements (database, schema, table)
1292 $table = explode( '.', $table );
1293 while ( count( $table ) < 3 ) {
1294 array_unshift( $table, false );
1302 * @param string $tableName
1303 * @param string $fName
1304 * @return bool|ResultWrapper
1307 public function dropTable( $tableName, $fName = __METHOD__
) {
1308 if ( !$this->tableExists( $tableName, $fName ) ) {
1312 // parent function incorrectly appends CASCADE, which we don't want
1313 $sql = "DROP TABLE " . $this->tableName( $tableName );
1315 return $this->query( $sql, $fName );
1319 * Called in the installer and updater.
1320 * Probably doesn't need to be called anywhere else in the codebase.
1321 * @param bool|null $value
1324 public function prepareStatements( $value = null ) {
1325 $old = $this->mPrepareStatements
;
1326 if ( $value !== null ) {
1327 $this->mPrepareStatements
= $value;
1334 * Called in the installer and updater.
1335 * Probably doesn't need to be called anywhere else in the codebase.
1336 * @param bool|null $value
1339 public function scrollableCursor( $value = null ) {
1340 $old = $this->mScrollableCursor
;
1341 if ( $value !== null ) {
1342 $this->mScrollableCursor
= $value;
1349 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );