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'];
362 protected function wasKnownStatementRollbackError() {
363 $errors = sqlsrv_errors( SQLSRV_ERR_ALL
);
367 // The transaction vs statement rollback behavior depends on XACT_ABORT, so make sure
368 // that the "statement has been terminated" error (3621) is specifically present.
369 // https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql
370 $statementOnly = false;
371 $codeWhitelist = [ '2601', '2627', '547' ];
372 foreach ( $errors as $error ) {
373 if ( $error['code'] == '3621' ) {
374 $statementOnly = true;
375 } elseif ( !in_array( $error['code'], $codeWhitelist ) ) {
376 $statementOnly = false;
381 return $statementOnly;
387 protected function fetchAffectedRowCount() {
388 return $this->lastAffectedRowCount
;
394 * @param mixed $table Array or string, table name(s) (prefix auto-added)
395 * @param mixed $vars Array or string, field name(s) to be retrieved
396 * @param mixed $conds Array or string, condition(s) for WHERE
397 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
398 * @param array $options Associative array of options (e.g.
399 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
400 * code for list of supported stuff
401 * @param array $join_conds Associative array of table join conditions
402 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
403 * @return mixed Database result resource (feed to Database::fetchObject
404 * or whatever), or false on failure
405 * @throws DBQueryError
406 * @throws DBUnexpectedError
409 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
410 $options = [], $join_conds = []
412 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
413 if ( isset( $options['EXPLAIN'] ) ) {
415 $this->scrollableCursor
= false;
416 $this->prepareStatements
= false;
417 $this->query( "SET SHOWPLAN_ALL ON" );
418 $ret = $this->query( $sql, $fname );
419 $this->query( "SET SHOWPLAN_ALL OFF" );
420 } catch ( DBQueryError
$dqe ) {
421 if ( isset( $options['FOR COUNT'] ) ) {
422 // likely don't have privs for SHOWPLAN, so run a select count instead
423 $this->query( "SET SHOWPLAN_ALL OFF" );
424 unset( $options['EXPLAIN'] );
425 $ret = $this->select(
427 'COUNT(*) AS EstimateRows',
434 // someone actually wanted the query plan instead of an est row count
435 // let them know of the error
436 $this->scrollableCursor
= true;
437 $this->prepareStatements
= true;
441 $this->scrollableCursor
= true;
442 $this->prepareStatements
= true;
445 return $this->query( $sql, $fname );
451 * @param mixed $table Array or string, table name(s) (prefix auto-added)
452 * @param mixed $vars Array or string, field name(s) to be retrieved
453 * @param mixed $conds Array or string, condition(s) for WHERE
454 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
455 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
456 * see Database::makeSelectOptions code for list of supported stuff
457 * @param array $join_conds Associative array of table join conditions (optional)
458 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
459 * @return string The SQL text
461 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
462 $options = [], $join_conds = []
464 if ( isset( $options['EXPLAIN'] ) ) {
465 unset( $options['EXPLAIN'] );
468 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
470 // try to rewrite aggregations of bit columns (currently MAX and MIN)
471 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
473 if ( is_array( $table ) ) {
476 $t = array_pop( $tables );
477 if ( is_array( $t ) ) {
478 $tables = array_merge( $tables, $t );
480 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
484 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
487 foreach ( $bitColumns as $col => $info ) {
489 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
490 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
492 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
499 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
502 $this->scrollableCursor
= false;
504 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
505 } catch ( Exception
$e ) {
506 $this->scrollableCursor
= true;
509 $this->scrollableCursor
= true;
512 public function delete( $table, $conds, $fname = __METHOD__
) {
513 $this->scrollableCursor
= false;
515 parent
::delete( $table, $conds, $fname );
516 } catch ( Exception
$e ) {
517 $this->scrollableCursor
= true;
520 $this->scrollableCursor
= true;
524 * Estimate rows in dataset
525 * Returns estimated count, based on SHOWPLAN_ALL output
526 * This is not necessarily an accurate estimate, so use sparingly
527 * Returns -1 if count cannot be found
528 * Takes same arguments as Database::select()
529 * @param string $table
531 * @param string $conds
532 * @param string $fname
533 * @param array $options
534 * @param array $join_conds
537 public function estimateRowCount( $table, $var = '*', $conds = '',
538 $fname = __METHOD__
, $options = [], $join_conds = []
540 $conds = $this->normalizeConditions( $conds, $fname );
541 $column = $this->extractSingleFieldFromList( $var );
542 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
543 $conds[] = "$column IS NOT NULL";
546 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
547 $options['EXPLAIN'] = true;
548 $options['FOR COUNT'] = true;
549 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
553 $row = $this->fetchRow( $res );
555 if ( isset( $row['EstimateRows'] ) ) {
556 $rows = (int)$row['EstimateRows'];
564 * Returns information about an index
565 * If errors are explicitly ignored, returns NULL on failure
566 * @param string $table
567 * @param string $index
568 * @param string $fname
569 * @return array|bool|null
571 public function indexInfo( $table, $index, $fname = __METHOD__
) {
572 # This does not return the same info as MYSQL would, but that's OK
573 # because MediaWiki never uses the returned value except to check for
574 # the existence of indexes.
575 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
576 $res = $this->query( $sql, $fname );
583 foreach ( $res as $row ) {
584 if ( $row->index_name
== $index ) {
585 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
586 $cols = explode( ", ", $row->index_keys
);
587 foreach ( $cols as $col ) {
588 $row->Column_name
= trim( $col );
589 $result[] = clone $row;
591 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
592 $row->Non_unique
= 0;
593 $cols = explode( ", ", $row->index_keys
);
594 foreach ( $cols as $col ) {
595 $row->Column_name
= trim( $col );
596 $result[] = clone $row;
601 return $result ?
: false;
605 * INSERT wrapper, inserts an array into a table
607 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
610 * Usually aborts on failure
611 * If errors are explicitly ignored, returns success
612 * @param string $table
613 * @param array $arrToInsert
614 * @param string $fname
615 * @param array $options
619 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
620 # No rows to insert, easy just return now
621 if ( !count( $arrToInsert ) ) {
625 if ( !is_array( $options ) ) {
626 $options = [ $options ];
629 $table = $this->tableName( $table );
631 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
632 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
635 // We know the table we're inserting into, get its identity column
637 // strip matching square brackets and the db/schema from table name
638 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
639 $tableRaw = array_pop( $tableRawArr );
640 $res = $this->doQuery(
641 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
642 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
644 if ( $res && sqlsrv_has_rows( $res ) ) {
645 // There is an identity for this table.
646 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
647 $identity = array_pop( $identityArr );
649 sqlsrv_free_stmt( $res );
651 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
652 $binaryColumns = $this->getBinaryColumns( $table );
654 // INSERT IGNORE is not supported by SQL Server
655 // remove IGNORE from options list and set ignore flag to true
656 if ( in_array( 'IGNORE', $options ) ) {
657 $options = array_diff( $options, [ 'IGNORE' ] );
658 $this->ignoreDupKeyErrors
= true;
662 foreach ( $arrToInsert as $a ) {
663 // start out with empty identity column, this is so we can return
664 // it as a result of the INSERT logic
667 $identityClause = '';
669 // if we have an identity column
672 foreach ( $a as $k => $v ) {
673 if ( $k == $identity ) {
674 if ( !is_null( $v ) ) {
675 // there is a value being passed to us,
676 // we need to turn on and off inserted identity
677 $sqlPre = "SET IDENTITY_INSERT $table ON;";
678 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
680 // we can't insert NULL into an identity column,
681 // so remove the column from the insert.
687 // we want to output an identity column as result
688 $identityClause = "OUTPUT INSERTED.$identity ";
691 $keys = array_keys( $a );
693 // Build the actual query
694 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
695 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
698 foreach ( $a as $key => $value ) {
699 if ( isset( $binaryColumns[$key] ) ) {
700 $value = new MssqlBlob( $value );
707 if ( is_null( $value ) ) {
709 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
710 if ( is_object( $value ) && $value instanceof Blob
) {
711 $sql .= $this->addQuotes( $value );
713 $sql .= $this->addQuotes( serialize( $value ) );
716 $sql .= $this->addQuotes( $value );
719 $sql .= ')' . $sqlPost;
722 $this->scrollableCursor
= false;
724 $ret = $this->query( $sql );
725 } catch ( Exception
$e ) {
726 $this->scrollableCursor
= true;
727 $this->ignoreDupKeyErrors
= false;
730 $this->scrollableCursor
= true;
732 if ( $ret instanceof ResultWrapper
&& !is_null( $identity ) ) {
733 // Then we want to get the identity column value we were assigned and save it off
734 $row = $ret->fetchObject();
735 if ( is_object( $row ) ) {
736 $this->lastInsertId
= $row->$identity;
737 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
738 // used if we got an identity back, we know for sure a row was affected, so
740 if ( $this->lastAffectedRowCount
== -1 ) {
741 $this->lastAffectedRowCount
= 1;
747 $this->ignoreDupKeyErrors
= false;
753 * INSERT SELECT wrapper
754 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
755 * Source items may be literals rather than field names, but strings should
756 * be quoted with Database::addQuotes().
757 * @param string $destTable
758 * @param array|string $srcTable May be an array of tables.
759 * @param array $varMap
760 * @param array $conds May be "*" to copy the whole table.
761 * @param string $fname
762 * @param array $insertOptions
763 * @param array $selectOptions
764 * @param array $selectJoinConds
768 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
769 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
771 $this->scrollableCursor
= false;
773 $ret = parent
::nativeInsertSelect(
783 } catch ( Exception
$e ) {
784 $this->scrollableCursor
= true;
787 $this->scrollableCursor
= true;
793 * UPDATE wrapper. Takes a condition array and a SET array.
795 * @param string $table Name of the table to UPDATE. This will be passed through
796 * Database::tableName().
798 * @param array $values An array of values to SET. For each array element,
799 * the key gives the field name, and the value gives the data
800 * to set that field to. The data will be quoted by
801 * Database::addQuotes().
803 * @param array $conds An array of conditions (WHERE). See
804 * Database::select() for the details of the format of
805 * condition arrays. Use '*' to update all rows.
807 * @param string $fname The function name of the caller (from __METHOD__),
808 * for logging and profiling.
810 * @param array $options An array of UPDATE options, can be:
811 * - IGNORE: Ignore unique key conflicts
812 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
814 * @throws DBUnexpectedError
817 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
818 $table = $this->tableName( $table );
819 $binaryColumns = $this->getBinaryColumns( $table );
821 $opts = $this->makeUpdateOptions( $options );
822 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
824 if ( $conds !== [] && $conds !== '*' ) {
825 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
828 $this->scrollableCursor
= false;
830 $this->query( $sql );
831 } catch ( Exception
$e ) {
832 $this->scrollableCursor
= true;
835 $this->scrollableCursor
= true;
840 * Makes an encoded list of strings from an array
841 * @param array $a Containing the data
842 * @param int $mode Constant
843 * - LIST_COMMA: comma separated, no field names
844 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
845 * the documentation for $conds in Database::select().
846 * - LIST_OR: ORed WHERE clause (without the WHERE)
847 * - LIST_SET: comma separated with field names, like a SET clause
848 * - LIST_NAMES: comma separated field names
849 * @param array $binaryColumns Contains a list of column names that are binary types
850 * This is a custom parameter only present for MS SQL.
852 * @throws DBUnexpectedError
855 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
856 if ( !is_array( $a ) ) {
857 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
860 if ( $mode != LIST_NAMES
) {
861 // In MS SQL, values need to be specially encoded when they are
862 // inserted into binary fields. Perform this necessary encoding
863 // for the specified set of columns.
864 foreach ( array_keys( $a ) as $field ) {
865 if ( !isset( $binaryColumns[$field] ) ) {
869 if ( is_array( $a[$field] ) ) {
870 foreach ( $a[$field] as &$v ) {
871 $v = new MssqlBlob( $v );
875 $a[$field] = new MssqlBlob( $a[$field] );
880 return parent
::makeList( $a, $mode );
884 * @param string $table
885 * @param string $field
886 * @return int Returns the size of a text field, or -1 for "unlimited"
888 public function textFieldSize( $table, $field ) {
889 $table = $this->tableName( $table );
890 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
891 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
892 $res = $this->query( $sql );
893 $row = $this->fetchRow( $res );
895 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
896 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
903 * Construct a LIMIT query with optional offset
904 * This is used for query pages
906 * @param string $sql SQL query we will append the limit too
907 * @param int $limit The SQL limit
908 * @param bool|int $offset The SQL offset (default false)
909 * @return array|string
910 * @throws DBUnexpectedError
912 public function limitResult( $sql, $limit, $offset = false ) {
913 if ( $offset === false ||
$offset == 0 ) {
914 if ( strpos( $sql, "SELECT" ) === false ) {
915 return "TOP {$limit} " . $sql;
917 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
918 'SELECT$1 TOP ' . $limit, $sql, 1 );
921 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
922 $select = $orderby = [];
923 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
924 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
926 $first = $offset +
1;
927 $last = $offset +
$limit;
928 $sub1 = 'sub_' . $this->subqueryId
;
929 $sub2 = 'sub_' . ( $this->subqueryId +
1 );
930 $this->subqueryId +
= 2;
933 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
937 $overOrder = 'ORDER BY (SELECT 1)';
939 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
940 // don't need to strip it out if we're using a FOR XML clause
941 $sql = str_replace( $orderby[1], '', $sql );
943 $overOrder = $orderby[1];
944 $postOrder = ' ' . $overOrder;
946 $sql = "SELECT {$select[1]}
948 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
949 FROM ({$sql}) {$sub1}
951 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
958 * If there is a limit clause, parse it, strip it, and pass the remaining
959 * SQL through limitResult() with the appropriate parameters. Not the
960 * prettiest solution, but better than building a whole new parser. This
961 * exists becase there are still too many extensions that don't use dynamic
965 * @return array|mixed|string
967 public function LimitToTopN( $sql ) {
968 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
969 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
970 if ( preg_match( $pattern, $sql, $matches ) ) {
971 $row_count = $matches[4];
972 $offset = $matches[3] ?
: $matches[6] ?
: false;
974 // strip the matching LIMIT clause out
975 $sql = str_replace( $matches[0], '', $sql );
977 return $this->limitResult( $sql, $row_count, $offset );
984 * @return string Wikitext of a link to the server software's web site
986 public function getSoftwareLink() {
987 return "[{{int:version-db-mssql-url}} MS SQL Server]";
991 * @return string Version information from the database
993 public function getServerVersion() {
994 $server_info = sqlsrv_server_info( $this->conn
);
996 if ( isset( $server_info['SQLServerVersion'] ) ) {
997 $version = $server_info['SQLServerVersion'];
1004 * @param string $table
1005 * @param string $fname
1008 public function tableExists( $table, $fname = __METHOD__
) {
1009 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1011 if ( $db !== false ) {
1013 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
1017 if ( $schema === false ) {
1018 $schema = $this->schema
;
1021 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1022 WHERE TABLE_TYPE = 'BASE TABLE'
1023 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1025 if ( $res->numRows() ) {
1033 * Query whether a given column exists in the mediawiki schema
1034 * @param string $table
1035 * @param string $field
1036 * @param string $fname
1039 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1040 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1042 if ( $db !== false ) {
1044 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1048 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1049 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1051 if ( $res->numRows() ) {
1058 public function fieldInfo( $table, $field ) {
1059 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1061 if ( $db !== false ) {
1063 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1067 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1068 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1070 $meta = $res->fetchRow();
1072 return new MssqlField( $meta );
1078 protected function doSavepoint( $identifier, $fname ) {
1079 $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1082 protected function doReleaseSavepoint( $identifier, $fname ) {
1083 // Not supported. Also not really needed, a new doSavepoint() for the
1084 // same identifier will overwrite the old.
1087 protected function doRollbackToSavepoint( $identifier, $fname ) {
1088 $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1092 * Begin a transaction, committing any previously open transaction
1093 * @param string $fname
1095 protected function doBegin( $fname = __METHOD__
) {
1096 sqlsrv_begin_transaction( $this->conn
);
1097 $this->trxLevel
= 1;
1102 * @param string $fname
1104 protected function doCommit( $fname = __METHOD__
) {
1105 sqlsrv_commit( $this->conn
);
1106 $this->trxLevel
= 0;
1110 * Rollback a transaction.
1111 * No-op on non-transactional databases.
1112 * @param string $fname
1114 protected function doRollback( $fname = __METHOD__
) {
1115 sqlsrv_rollback( $this->conn
);
1116 $this->trxLevel
= 0;
1123 public function strencode( $s ) {
1124 // Should not be called by us
1125 return str_replace( "'", "''", $s );
1129 * @param string|int|null|bool|Blob $s
1130 * @return string|int
1132 public function addQuotes( $s ) {
1133 if ( $s instanceof MssqlBlob
) {
1135 } elseif ( $s instanceof Blob
) {
1136 // this shouldn't really ever be called, but it's here if needed
1137 // (and will quite possibly make the SQL error out)
1138 $blob = new MssqlBlob( $s->fetch() );
1139 return $blob->fetch();
1141 if ( is_bool( $s ) ) {
1144 return parent
::addQuotes( $s );
1152 public function addIdentifierQuotes( $s ) {
1153 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1154 return '[' . $s . ']';
1158 * @param string $name
1161 public function isQuotedIdentifier( $name ) {
1162 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1166 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1169 * @param string $escapeChar
1172 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1173 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1174 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1175 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1183 public function selectDB( $db ) {
1185 $this->dbName
= $db;
1186 $this->query( "USE $db" );
1188 } catch ( Exception
$e ) {
1194 * @param array $options An associative array of options to be turned into
1195 * an SQL query, valid keys are listed in the function.
1198 public function makeSelectOptions( $options ) {
1203 foreach ( $options as $key => $option ) {
1204 if ( is_numeric( $key ) ) {
1205 $noKeyOptions[$option] = true;
1209 $tailOpts .= $this->makeGroupByWithHaving( $options );
1211 $tailOpts .= $this->makeOrderBy( $options );
1213 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1214 $startOpts .= 'DISTINCT';
1217 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1218 // used in group concat field emulation
1219 $tailOpts .= " FOR XML PATH('')";
1222 // we want this to be compatible with the output of parent::makeSelectOptions()
1223 return [ $startOpts, '', $tailOpts, '', '' ];
1226 public function getType() {
1231 * @param array $stringList
1234 public function buildConcat( $stringList ) {
1235 return implode( ' + ', $stringList );
1239 * Build a GROUP_CONCAT or equivalent statement for a query.
1240 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1242 * This is useful for combining a field for several rows into a single string.
1243 * NULL values will not appear in the output, duplicated values will appear,
1244 * and the resulting delimiter-separated values have no defined sort order.
1245 * Code using the results may need to use the PHP unique() or sort() methods.
1247 * @param string $delim Glue to bind the results together
1248 * @param string|array $table Table name
1249 * @param string $field Field name
1250 * @param string|array $conds Conditions
1251 * @param string|array $join_conds Join conditions
1252 * @return string SQL text
1255 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1258 $gcsq = 'gcsq_' . $this->subqueryId
;
1259 $this->subqueryId++
;
1261 $delimLen = strlen( $delim );
1262 $fld = "{$field} + {$this->addQuotes( $delim )}";
1263 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1264 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1265 . ") {$gcsq} ({$field}))";
1270 public function buildSubstring( $input, $startPosition, $length = null ) {
1271 $this->assertBuildSubstringParams( $startPosition, $length );
1272 if ( $length === null ) {
1274 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1275 * length returned use the default maximum size of text.
1276 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1278 $length = 2147483647;
1280 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1284 * Returns an associative array for fields that are of type varbinary, binary, or image
1285 * $table can be either a raw table name or passed through tableName() first
1286 * @param string $table
1289 private function getBinaryColumns( $table ) {
1290 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1291 $tableRaw = array_pop( $tableRawArr );
1293 if ( $this->binaryColumnCache
=== null ) {
1294 $this->populateColumnCaches();
1297 return isset( $this->binaryColumnCache
[$tableRaw] )
1298 ?
$this->binaryColumnCache
[$tableRaw]
1303 * @param string $table
1306 private function getBitColumns( $table ) {
1307 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1308 $tableRaw = array_pop( $tableRawArr );
1310 if ( $this->bitColumnCache
=== null ) {
1311 $this->populateColumnCaches();
1314 return isset( $this->bitColumnCache
[$tableRaw] )
1315 ?
$this->bitColumnCache
[$tableRaw]
1319 private function populateColumnCaches() {
1320 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1322 'TABLE_CATALOG' => $this->dbName
,
1323 'TABLE_SCHEMA' => $this->schema
,
1324 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1327 $this->binaryColumnCache
= [];
1328 $this->bitColumnCache
= [];
1329 foreach ( $res as $row ) {
1330 if ( $row->DATA_TYPE
== 'bit' ) {
1331 $this->bitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1333 $this->binaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1339 * @param string $name
1340 * @param string $format
1343 function tableName( $name, $format = 'quoted' ) {
1344 # Replace reserved words with better ones
1347 return $this->realTableName( 'mwuser', $format );
1349 return $this->realTableName( $name, $format );
1354 * call this instead of tableName() in the updater when renaming tables
1355 * @param string $name
1356 * @param string $format One of quoted, raw, or split
1359 function realTableName( $name, $format = 'quoted' ) {
1360 $table = parent
::tableName( $name, $format );
1361 if ( $format == 'split' ) {
1362 // Used internally, we want the schema split off from the table name and returned
1363 // as a list with 3 elements (database, schema, table)
1364 $table = explode( '.', $table );
1365 while ( count( $table ) < 3 ) {
1366 array_unshift( $table, false );
1374 * @param string $tableName
1375 * @param string $fName
1376 * @return bool|ResultWrapper
1379 public function dropTable( $tableName, $fName = __METHOD__
) {
1380 if ( !$this->tableExists( $tableName, $fName ) ) {
1384 // parent function incorrectly appends CASCADE, which we don't want
1385 $sql = "DROP TABLE " . $this->tableName( $tableName );
1387 return $this->query( $sql, $fName );
1391 * Called in the installer and updater.
1392 * Probably doesn't need to be called anywhere else in the codebase.
1393 * @param bool|null $value
1396 public function prepareStatements( $value = null ) {
1397 $old = $this->prepareStatements
;
1398 if ( $value !== null ) {
1399 $this->prepareStatements
= $value;
1406 * Called in the installer and updater.
1407 * Probably doesn't need to be called anywhere else in the codebase.
1408 * @param bool|null $value
1411 public function scrollableCursor( $value = null ) {
1412 $old = $this->scrollableCursor
;
1413 if ( $value !== null ) {
1414 $this->scrollableCursor
= $value;
1421 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );