Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[lhc/web/wiklou.git] / includes / libs / rdbms / database / DatabaseMssql.php
1 <?php
2 /**
3 * This is the MS SQL Server Native database abstraction layer.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Database
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>
26 */
27
28 namespace Wikimedia\Rdbms;
29
30 use Exception;
31 use RuntimeException;
32 use stdClass;
33 use Wikimedia\AtEase\AtEase;
34
35 /**
36 * @ingroup Database
37 */
38 class DatabaseMssql extends Database {
39 /** @var int */
40 protected $serverPort;
41 /** @var bool */
42 protected $useWindowsAuth = false;
43 /** @var int|null */
44 protected $lastInsertId = null;
45 /** @var int|null */
46 protected $lastAffectedRowCount = null;
47 /** @var int */
48 protected $subqueryId = 0;
49 /** @var bool */
50 protected $scrollableCursor = true;
51 /** @var bool */
52 protected $prepareStatements = true;
53 /** @var stdClass[][]|null */
54 protected $binaryColumnCache = null;
55 /** @var stdClass[][]|null */
56 protected $bitColumnCache = null;
57 /** @var bool */
58 protected $ignoreDupKeyErrors = false;
59 /** @var string[] */
60 protected $ignoreErrors = [];
61
62 public function implicitGroupby() {
63 return false;
64 }
65
66 public function implicitOrderby() {
67 return false;
68 }
69
70 public function unionSupportsOrderAndLimit() {
71 return false;
72 }
73
74 public function __construct( array $params ) {
75 $this->serverPort = $params['port'];
76 $this->useWindowsAuth = $params['UseWindowsAuth'];
77
78 parent::__construct( $params );
79 }
80
81 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
82 // Test for driver support, to avoid suppressed fatal error
83 if ( !function_exists( 'sqlsrv_connect' ) ) {
84 throw new DBConnectionError(
85 $this,
86 "Microsoft SQL Server Native (sqlsrv) functions missing.
87 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
88 );
89 }
90
91 $this->close();
92 $this->server = $server;
93 $this->user = $user;
94 $this->password = $password;
95
96 $connectionInfo = [];
97
98 if ( $dbName != '' ) {
99 $connectionInfo['Database'] = $dbName;
100 }
101
102 // Decide which auth scenerio to use
103 // if we are using Windows auth, then don't add credentials to $connectionInfo
104 if ( !$this->useWindowsAuth ) {
105 $connectionInfo['UID'] = $user;
106 $connectionInfo['PWD'] = $password;
107 }
108
109 AtEase::suppressWarnings();
110 $this->conn = sqlsrv_connect( $server, $connectionInfo );
111 AtEase::restoreWarnings();
112
113 if ( $this->conn === false ) {
114 $error = $this->lastError();
115 $this->connLogger->error(
116 "Error connecting to {db_server}: {error}",
117 $this->getLogContext( [ 'method' => __METHOD__, 'error' => $error ] )
118 );
119 throw new DBConnectionError( $this, $error );
120 }
121
122 $this->currentDomain = new DatabaseDomain(
123 ( $dbName != '' ) ? $dbName : null,
124 null,
125 $tablePrefix
126 );
127
128 return (bool)$this->conn;
129 }
130
131 /**
132 * Closes a database connection, if it is open
133 * Returns success, true if already closed
134 * @return bool
135 */
136 protected function closeConnection() {
137 return sqlsrv_close( $this->conn );
138 }
139
140 /**
141 * @param bool|MssqlResultWrapper|resource $result
142 * @return bool|MssqlResultWrapper
143 */
144 protected function resultObject( $result ) {
145 if ( !$result ) {
146 return false;
147 } elseif ( $result instanceof MssqlResultWrapper ) {
148 return $result;
149 } elseif ( $result === true ) {
150 // Successful write query
151 return $result;
152 } else {
153 return new MssqlResultWrapper( $this, $result );
154 }
155 }
156
157 /**
158 * @param string $sql
159 * @return bool|MssqlResultWrapper|resource
160 */
161 protected function doQuery( $sql ) {
162 // several extensions seem to think that all databases support limits
163 // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
164 // so to catch any of those extensions we'll do a quick check for a
165 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
166 // the LIMIT clause and passes the result to $this->limitResult();
167 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
168 // massage LIMIT -> TopN
169 $sql = $this->LimitToTopN( $sql );
170 }
171
172 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
173 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
174 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
175 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
176 }
177
178 // perform query
179
180 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
181 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
182 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
183 // strings make php throw a fatal error "Severe error translating Unicode"
184 if ( $this->scrollableCursor ) {
185 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC ];
186 } else {
187 $scrollArr = [];
188 }
189
190 if ( $this->prepareStatements ) {
191 // we do prepare + execute so we can get its field metadata for later usage if desired
192 $stmt = sqlsrv_prepare( $this->conn, $sql, [], $scrollArr );
193 $success = sqlsrv_execute( $stmt );
194 } else {
195 $stmt = sqlsrv_query( $this->conn, $sql, [], $scrollArr );
196 $success = (bool)$stmt;
197 }
198
199 // Make a copy to ensure what we add below does not get reflected in future queries
200 $ignoreErrors = $this->ignoreErrors;
201
202 if ( $this->ignoreDupKeyErrors ) {
203 // ignore duplicate key errors
204 // this emulates INSERT IGNORE in MySQL
205 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
206 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
207 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
208 }
209
210 if ( $success === false ) {
211 $errors = sqlsrv_errors();
212 $success = true;
213
214 foreach ( $errors as $err ) {
215 if ( !in_array( $err['code'], $ignoreErrors ) ) {
216 $success = false;
217 break;
218 }
219 }
220
221 if ( $success === false ) {
222 return false;
223 }
224 }
225 // remember number of rows affected
226 $this->lastAffectedRowCount = sqlsrv_rows_affected( $stmt );
227
228 return $stmt;
229 }
230
231 public function freeResult( $res ) {
232 sqlsrv_free_stmt( ResultWrapper::unwrap( $res ) );
233 }
234
235 /**
236 * @param IResultWrapper $res
237 * @return stdClass
238 */
239 public function fetchObject( $res ) {
240 // $res is expected to be an instance of MssqlResultWrapper here
241 return $res->fetchObject();
242 }
243
244 /**
245 * @param IResultWrapper $res
246 * @return array
247 */
248 public function fetchRow( $res ) {
249 return $res->fetchRow();
250 }
251
252 /**
253 * @param mixed $res
254 * @return int
255 */
256 public function numRows( $res ) {
257 $res = ResultWrapper::unwrap( $res );
258
259 $ret = sqlsrv_num_rows( $res );
260 if ( $ret === false ) {
261 // we cannot get an amount of rows from this cursor type
262 // has_rows returns bool true/false if the result has rows
263 $ret = (int)sqlsrv_has_rows( $res );
264 }
265
266 return $ret;
267 }
268
269 /**
270 * @param mixed $res
271 * @return int
272 */
273 public function numFields( $res ) {
274 return sqlsrv_num_fields( ResultWrapper::unwrap( $res ) );
275 }
276
277 /**
278 * @param mixed $res
279 * @param int $n
280 * @return int
281 */
282 public function fieldName( $res, $n ) {
283 return sqlsrv_field_metadata( ResultWrapper::unwrap( $res ) )[$n]['Name'];
284 }
285
286 /**
287 * This must be called after nextSequenceVal
288 * @return int|null
289 */
290 public function insertId() {
291 return $this->lastInsertId;
292 }
293
294 /**
295 * @param MssqlResultWrapper $res
296 * @param int $row
297 * @return bool
298 */
299 public function dataSeek( $res, $row ) {
300 return $res->seek( $row );
301 }
302
303 /**
304 * @return string
305 */
306 public function lastError() {
307 $strRet = '';
308 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL );
309 if ( $retErrors != null ) {
310 foreach ( $retErrors as $arrError ) {
311 $strRet .= $this->formatError( $arrError ) . "\n";
312 }
313 } else {
314 $strRet = "No errors found";
315 }
316
317 return $strRet;
318 }
319
320 /**
321 * @param array $err
322 * @return string
323 */
324 private function formatError( $err ) {
325 return '[SQLSTATE ' .
326 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
327 }
328
329 /**
330 * @return string|int
331 */
332 public function lastErrno() {
333 $err = sqlsrv_errors( SQLSRV_ERR_ALL );
334 if ( $err !== null && isset( $err[0] ) ) {
335 return $err[0]['code'];
336 } else {
337 return 0;
338 }
339 }
340
341 protected function wasKnownStatementRollbackError() {
342 $errors = sqlsrv_errors( SQLSRV_ERR_ALL );
343 if ( !$errors ) {
344 return false;
345 }
346 // The transaction vs statement rollback behavior depends on XACT_ABORT, so make sure
347 // that the "statement has been terminated" error (3621) is specifically present.
348 // https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql
349 $statementOnly = false;
350 $codeWhitelist = [ '2601', '2627', '547' ];
351 foreach ( $errors as $error ) {
352 if ( $error['code'] == '3621' ) {
353 $statementOnly = true;
354 } elseif ( !in_array( $error['code'], $codeWhitelist ) ) {
355 $statementOnly = false;
356 break;
357 }
358 }
359
360 return $statementOnly;
361 }
362
363 public function serverIsReadOnly() {
364 $encDatabase = $this->addQuotes( $this->getDBname() );
365 $res = $this->query(
366 "SELECT IS_READ_ONLY FROM SYS.DATABASES WHERE NAME = $encDatabase",
367 __METHOD__
368 );
369 $row = $this->fetchObject( $res );
370
371 return $row ? (bool)$row->IS_READ_ONLY : false;
372 }
373
374 /**
375 * @return int
376 */
377 protected function fetchAffectedRowCount() {
378 return $this->lastAffectedRowCount;
379 }
380
381 /**
382 * SELECT wrapper
383 *
384 * @param mixed $table Array or string, table name(s) (prefix auto-added)
385 * @param mixed $vars Array or string, field name(s) to be retrieved
386 * @param mixed $conds Array or string, condition(s) for WHERE
387 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
388 * @param array $options Associative array of options (e.g.
389 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
390 * code for list of supported stuff
391 * @param array $join_conds Associative array of table join conditions
392 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
393 * @return mixed Database result resource (feed to Database::fetchObject
394 * or whatever), or false on failure
395 * @throws DBQueryError
396 * @throws DBUnexpectedError
397 * @throws Exception
398 */
399 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
400 $options = [], $join_conds = []
401 ) {
402 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
403 if ( isset( $options['EXPLAIN'] ) ) {
404 try {
405 $this->scrollableCursor = false;
406 $this->prepareStatements = false;
407 $this->query( "SET SHOWPLAN_ALL ON" );
408 $ret = $this->query( $sql, $fname );
409 $this->query( "SET SHOWPLAN_ALL OFF" );
410 } catch ( DBQueryError $dqe ) {
411 if ( isset( $options['FOR COUNT'] ) ) {
412 // likely don't have privs for SHOWPLAN, so run a select count instead
413 $this->query( "SET SHOWPLAN_ALL OFF" );
414 unset( $options['EXPLAIN'] );
415 $ret = $this->select(
416 $table,
417 'COUNT(*) AS EstimateRows',
418 $conds,
419 $fname,
420 $options,
421 $join_conds
422 );
423 } else {
424 // someone actually wanted the query plan instead of an est row count
425 // let them know of the error
426 $this->scrollableCursor = true;
427 $this->prepareStatements = true;
428 throw $dqe;
429 }
430 }
431 $this->scrollableCursor = true;
432 $this->prepareStatements = true;
433 return $ret;
434 }
435 return $this->query( $sql, $fname );
436 }
437
438 /**
439 * SELECT wrapper
440 *
441 * @param mixed $table Array or string, table name(s) (prefix auto-added)
442 * @param mixed $vars Array or string, field name(s) to be retrieved
443 * @param mixed $conds Array or string, condition(s) for WHERE
444 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
445 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
446 * see Database::makeSelectOptions code for list of supported stuff
447 * @param array $join_conds Associative array of table join conditions (optional)
448 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
449 * @return string The SQL text
450 */
451 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
452 $options = [], $join_conds = []
453 ) {
454 if ( isset( $options['EXPLAIN'] ) ) {
455 unset( $options['EXPLAIN'] );
456 }
457
458 $sql = parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
459
460 // try to rewrite aggregations of bit columns (currently MAX and MIN)
461 if ( strpos( $sql, 'MAX(' ) !== false || strpos( $sql, 'MIN(' ) !== false ) {
462 $bitColumns = [];
463 if ( is_array( $table ) ) {
464 $tables = $table;
465 while ( $tables ) {
466 $t = array_pop( $tables );
467 if ( is_array( $t ) ) {
468 $tables = array_merge( $tables, $t );
469 } else {
470 $bitColumns += $this->getBitColumns( $this->tableName( $t ) );
471 }
472 }
473 } else {
474 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
475 }
476
477 foreach ( $bitColumns as $col => $info ) {
478 $replace = [
479 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
480 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
481 ];
482 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
483 }
484 }
485
486 return $sql;
487 }
488
489 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
490 $fname = __METHOD__
491 ) {
492 $this->scrollableCursor = false;
493 try {
494 parent::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
495 } catch ( Exception $e ) {
496 $this->scrollableCursor = true;
497 throw $e;
498 }
499 $this->scrollableCursor = true;
500 }
501
502 public function delete( $table, $conds, $fname = __METHOD__ ) {
503 $this->scrollableCursor = false;
504 try {
505 parent::delete( $table, $conds, $fname );
506 } catch ( Exception $e ) {
507 $this->scrollableCursor = true;
508 throw $e;
509 }
510 $this->scrollableCursor = true;
511
512 return true;
513 }
514
515 /**
516 * Estimate rows in dataset
517 * Returns estimated count, based on SHOWPLAN_ALL output
518 * This is not necessarily an accurate estimate, so use sparingly
519 * Returns -1 if count cannot be found
520 * Takes same arguments as Database::select()
521 * @param string $table
522 * @param string $var
523 * @param string $conds
524 * @param string $fname
525 * @param array $options
526 * @param array $join_conds
527 * @return int
528 */
529 public function estimateRowCount( $table, $var = '*', $conds = '',
530 $fname = __METHOD__, $options = [], $join_conds = []
531 ) {
532 $conds = $this->normalizeConditions( $conds, $fname );
533 $column = $this->extractSingleFieldFromList( $var );
534 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
535 $conds[] = "$column IS NOT NULL";
536 }
537
538 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
539 $options['EXPLAIN'] = true;
540 $options['FOR COUNT'] = true;
541 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
542
543 $rows = -1;
544 if ( $res ) {
545 $row = $this->fetchRow( $res );
546
547 if ( isset( $row['EstimateRows'] ) ) {
548 $rows = (int)$row['EstimateRows'];
549 }
550 }
551
552 return $rows;
553 }
554
555 /**
556 * Returns information about an index
557 * If errors are explicitly ignored, returns NULL on failure
558 * @param string $table
559 * @param string $index
560 * @param string $fname
561 * @return array|bool|null
562 */
563 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
564 # This does not return the same info as MYSQL would, but that's OK
565 # because MediaWiki never uses the returned value except to check for
566 # the existence of indexes.
567 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
568 $res = $this->query( $sql, $fname );
569
570 if ( !$res ) {
571 return null;
572 }
573
574 $result = [];
575 foreach ( $res as $row ) {
576 if ( $row->index_name == $index ) {
577 $row->Non_unique = !stristr( $row->index_description, "unique" );
578 $cols = explode( ", ", $row->index_keys );
579 foreach ( $cols as $col ) {
580 $row->Column_name = trim( $col );
581 $result[] = clone $row;
582 }
583 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description, 'PRIMARY' ) ) {
584 $row->Non_unique = 0;
585 $cols = explode( ", ", $row->index_keys );
586 foreach ( $cols as $col ) {
587 $row->Column_name = trim( $col );
588 $result[] = clone $row;
589 }
590 }
591 }
592
593 return $result ?: false;
594 }
595
596 /**
597 * INSERT wrapper, inserts an array into a table
598 *
599 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
600 * multi-row insert.
601 *
602 * Usually aborts on failure
603 * If errors are explicitly ignored, returns success
604 * @param string $table
605 * @param array $arrToInsert
606 * @param string $fname
607 * @param array $options
608 * @return bool
609 * @throws Exception
610 */
611 public function insert( $table, $arrToInsert, $fname = __METHOD__, $options = [] ) {
612 # No rows to insert, easy just return now
613 if ( !count( $arrToInsert ) ) {
614 return true;
615 }
616
617 if ( !is_array( $options ) ) {
618 $options = [ $options ];
619 }
620
621 $table = $this->tableName( $table );
622
623 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
624 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
625 }
626
627 // We know the table we're inserting into, get its identity column
628 $identity = null;
629 // strip matching square brackets and the db/schema from table name
630 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
631 $tableRaw = array_pop( $tableRawArr );
632 $res = $this->doQuery(
633 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
634 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
635 );
636 if ( $res && sqlsrv_has_rows( $res ) ) {
637 // There is an identity for this table.
638 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC );
639 $identity = array_pop( $identityArr );
640 }
641 sqlsrv_free_stmt( $res );
642
643 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
644 $binaryColumns = $this->getBinaryColumns( $table );
645
646 // INSERT IGNORE is not supported by SQL Server
647 // remove IGNORE from options list and set ignore flag to true
648 if ( in_array( 'IGNORE', $options ) ) {
649 $options = array_diff( $options, [ 'IGNORE' ] );
650 $this->ignoreDupKeyErrors = true;
651 }
652
653 $ret = null;
654 foreach ( $arrToInsert as $a ) {
655 // start out with empty identity column, this is so we can return
656 // it as a result of the INSERT logic
657 $sqlPre = '';
658 $sqlPost = '';
659 $identityClause = '';
660
661 // if we have an identity column
662 if ( $identity ) {
663 // iterate through
664 foreach ( $a as $k => $v ) {
665 if ( $k == $identity ) {
666 if ( !is_null( $v ) ) {
667 // there is a value being passed to us,
668 // we need to turn on and off inserted identity
669 $sqlPre = "SET IDENTITY_INSERT $table ON;";
670 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
671 } else {
672 // we can't insert NULL into an identity column,
673 // so remove the column from the insert.
674 unset( $a[$k] );
675 }
676 }
677 }
678
679 // we want to output an identity column as result
680 $identityClause = "OUTPUT INSERTED.$identity ";
681 }
682
683 $keys = array_keys( $a );
684
685 // Build the actual query
686 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
687 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
688
689 $first = true;
690 foreach ( $a as $key => $value ) {
691 if ( isset( $binaryColumns[$key] ) ) {
692 $value = new MssqlBlob( $value );
693 }
694 if ( $first ) {
695 $first = false;
696 } else {
697 $sql .= ',';
698 }
699 if ( is_null( $value ) ) {
700 $sql .= 'null';
701 } else {
702 $sql .= $this->addQuotes( $value );
703 }
704 }
705 $sql .= ')' . $sqlPost;
706
707 // Run the query
708 $this->scrollableCursor = false;
709 try {
710 $ret = $this->query( $sql );
711 } catch ( Exception $e ) {
712 $this->scrollableCursor = true;
713 $this->ignoreDupKeyErrors = false;
714 throw $e;
715 }
716 $this->scrollableCursor = true;
717
718 if ( $ret instanceof IResultWrapper && !is_null( $identity ) ) {
719 // Then we want to get the identity column value we were assigned and save it off
720 $row = $ret->fetchObject();
721 if ( is_object( $row ) ) {
722 $this->lastInsertId = $row->$identity;
723 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
724 // used if we got an identity back, we know for sure a row was affected, so
725 // adjust that here
726 if ( $this->lastAffectedRowCount == -1 ) {
727 $this->lastAffectedRowCount = 1;
728 }
729 }
730 }
731 }
732
733 $this->ignoreDupKeyErrors = false;
734
735 return true;
736 }
737
738 /**
739 * INSERT SELECT wrapper
740 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
741 * Source items may be literals rather than field names, but strings should
742 * be quoted with Database::addQuotes().
743 * @param string $destTable
744 * @param array|string $srcTable May be an array of tables.
745 * @param array $varMap
746 * @param array $conds May be "*" to copy the whole table.
747 * @param string $fname
748 * @param array $insertOptions
749 * @param array $selectOptions
750 * @param array $selectJoinConds
751 * @throws Exception
752 */
753 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
754 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
755 ) {
756 $this->scrollableCursor = false;
757 try {
758 parent::nativeInsertSelect(
759 $destTable,
760 $srcTable,
761 $varMap,
762 $conds,
763 $fname,
764 $insertOptions,
765 $selectOptions,
766 $selectJoinConds
767 );
768 } catch ( Exception $e ) {
769 $this->scrollableCursor = true;
770 throw $e;
771 }
772 $this->scrollableCursor = true;
773 }
774
775 /**
776 * UPDATE wrapper. Takes a condition array and a SET array.
777 *
778 * @param string $table Name of the table to UPDATE. This will be passed through
779 * Database::tableName().
780 *
781 * @param array $values An array of values to SET. For each array element,
782 * the key gives the field name, and the value gives the data
783 * to set that field to. The data will be quoted by
784 * Database::addQuotes().
785 *
786 * @param array $conds An array of conditions (WHERE). See
787 * Database::select() for the details of the format of
788 * condition arrays. Use '*' to update all rows.
789 *
790 * @param string $fname The function name of the caller (from __METHOD__),
791 * for logging and profiling.
792 *
793 * @param array $options An array of UPDATE options, can be:
794 * - IGNORE: Ignore unique key conflicts
795 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
796 * @return bool
797 * @throws DBUnexpectedError
798 * @throws Exception
799 */
800 function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
801 $table = $this->tableName( $table );
802 $binaryColumns = $this->getBinaryColumns( $table );
803
804 $opts = $this->makeUpdateOptions( $options );
805 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET, $binaryColumns );
806
807 if ( $conds !== [] && $conds !== '*' ) {
808 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND, $binaryColumns );
809 }
810
811 $this->scrollableCursor = false;
812 try {
813 $this->query( $sql );
814 } catch ( Exception $e ) {
815 $this->scrollableCursor = true;
816 throw $e;
817 }
818 $this->scrollableCursor = true;
819 return true;
820 }
821
822 /**
823 * Makes an encoded list of strings from an array
824 * @param array $a Containing the data
825 * @param int $mode Constant
826 * - LIST_COMMA: comma separated, no field names
827 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
828 * the documentation for $conds in Database::select().
829 * - LIST_OR: ORed WHERE clause (without the WHERE)
830 * - LIST_SET: comma separated with field names, like a SET clause
831 * - LIST_NAMES: comma separated field names
832 * @param array $binaryColumns Contains a list of column names that are binary types
833 * This is a custom parameter only present for MS SQL.
834 *
835 * @throws DBUnexpectedError
836 * @return string
837 */
838 public function makeList( $a, $mode = LIST_COMMA, $binaryColumns = [] ) {
839 if ( !is_array( $a ) ) {
840 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
841 }
842
843 if ( $mode != LIST_NAMES ) {
844 // In MS SQL, values need to be specially encoded when they are
845 // inserted into binary fields. Perform this necessary encoding
846 // for the specified set of columns.
847 foreach ( array_keys( $a ) as $field ) {
848 if ( !isset( $binaryColumns[$field] ) ) {
849 continue;
850 }
851
852 if ( is_array( $a[$field] ) ) {
853 foreach ( $a[$field] as &$v ) {
854 $v = new MssqlBlob( $v );
855 }
856 unset( $v );
857 } else {
858 $a[$field] = new MssqlBlob( $a[$field] );
859 }
860 }
861 }
862
863 return parent::makeList( $a, $mode );
864 }
865
866 /**
867 * @param string $table
868 * @param string $field
869 * @return int Returns the size of a text field, or -1 for "unlimited"
870 */
871 public function textFieldSize( $table, $field ) {
872 $table = $this->tableName( $table );
873 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
874 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
875 $res = $this->query( $sql );
876 $row = $this->fetchRow( $res );
877 $size = -1;
878 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
879 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
880 }
881
882 return $size;
883 }
884
885 /**
886 * Construct a LIMIT query with optional offset
887 * This is used for query pages
888 *
889 * @param string $sql SQL query we will append the limit too
890 * @param int $limit The SQL limit
891 * @param bool|int $offset The SQL offset (default false)
892 * @return array|string
893 * @throws DBUnexpectedError
894 */
895 public function limitResult( $sql, $limit, $offset = false ) {
896 if ( $offset === false || $offset == 0 ) {
897 if ( strpos( $sql, "SELECT" ) === false ) {
898 return "TOP {$limit} " . $sql;
899 } else {
900 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
901 'SELECT$1 TOP ' . $limit, $sql, 1 );
902 }
903 } else {
904 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
905 $select = $orderby = [];
906 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
907 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
908 $postOrder = '';
909 $first = $offset + 1;
910 $last = $offset + $limit;
911 $sub1 = 'sub_' . $this->subqueryId;
912 $sub2 = 'sub_' . ( $this->subqueryId + 1 );
913 $this->subqueryId += 2;
914 if ( !$s1 ) {
915 // wat
916 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
917 }
918 if ( !$s2 ) {
919 // no ORDER BY
920 $overOrder = 'ORDER BY (SELECT 1)';
921 } else {
922 if ( !isset( $orderby[2] ) || !$orderby[2] ) {
923 // don't need to strip it out if we're using a FOR XML clause
924 $sql = str_replace( $orderby[1], '', $sql );
925 }
926 $overOrder = $orderby[1];
927 $postOrder = ' ' . $overOrder;
928 }
929 $sql = "SELECT {$select[1]}
930 FROM (
931 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
932 FROM ({$sql}) {$sub1}
933 ) {$sub2}
934 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
935
936 return $sql;
937 }
938 }
939
940 /**
941 * If there is a limit clause, parse it, strip it, and pass the remaining
942 * SQL through limitResult() with the appropriate parameters. Not the
943 * prettiest solution, but better than building a whole new parser. This
944 * exists becase there are still too many extensions that don't use dynamic
945 * sql generation.
946 *
947 * @param string $sql
948 * @return array|mixed|string
949 */
950 public function LimitToTopN( $sql ) {
951 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
952 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
953 if ( preg_match( $pattern, $sql, $matches ) ) {
954 $row_count = $matches[4];
955 $offset = $matches[3] ?: $matches[6] ?: false;
956
957 // strip the matching LIMIT clause out
958 $sql = str_replace( $matches[0], '', $sql );
959
960 return $this->limitResult( $sql, $row_count, $offset );
961 }
962
963 return $sql;
964 }
965
966 /**
967 * @return string Wikitext of a link to the server software's web site
968 */
969 public function getSoftwareLink() {
970 return "[{{int:version-db-mssql-url}} MS SQL Server]";
971 }
972
973 /**
974 * @return string Version information from the database
975 */
976 public function getServerVersion() {
977 $server_info = sqlsrv_server_info( $this->conn );
978 $version = $server_info['SQLServerVersion'] ?? 'Error';
979
980 return $version;
981 }
982
983 /**
984 * @param string $table
985 * @param string $fname
986 * @return bool
987 */
988 public function tableExists( $table, $fname = __METHOD__ ) {
989 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
990
991 if ( $db !== false ) {
992 // remote database
993 $this->queryLogger->error( "Attempting to call tableExists on a remote table" );
994 return false;
995 }
996
997 if ( $schema === false ) {
998 $schema = $this->dbSchema();
999 }
1000
1001 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1002 WHERE TABLE_TYPE = 'BASE TABLE'
1003 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1004
1005 if ( $res->numRows() ) {
1006 return true;
1007 } else {
1008 return false;
1009 }
1010 }
1011
1012 /**
1013 * Query whether a given column exists in the mediawiki schema
1014 * @param string $table
1015 * @param string $field
1016 * @param string $fname
1017 * @return bool
1018 */
1019 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1020 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1021
1022 if ( $db !== false ) {
1023 // remote database
1024 $this->queryLogger->error( "Attempting to call fieldExists on a remote table" );
1025 return false;
1026 }
1027
1028 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1029 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1030
1031 if ( $res->numRows() ) {
1032 return true;
1033 } else {
1034 return false;
1035 }
1036 }
1037
1038 public function fieldInfo( $table, $field ) {
1039 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1040
1041 if ( $db !== false ) {
1042 // remote database
1043 $this->queryLogger->error( "Attempting to call fieldInfo on a remote table" );
1044 return false;
1045 }
1046
1047 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1048 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1049
1050 $meta = $res->fetchRow();
1051 if ( $meta ) {
1052 return new MssqlField( $meta );
1053 }
1054
1055 return false;
1056 }
1057
1058 protected function doSavepoint( $identifier, $fname ) {
1059 $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1060 }
1061
1062 protected function doReleaseSavepoint( $identifier, $fname ) {
1063 // Not supported. Also not really needed, a new doSavepoint() for the
1064 // same identifier will overwrite the old.
1065 }
1066
1067 protected function doRollbackToSavepoint( $identifier, $fname ) {
1068 $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1069 }
1070
1071 protected function doBegin( $fname = __METHOD__ ) {
1072 if ( !sqlsrv_begin_transaction( $this->conn ) ) {
1073 $this->reportQueryError( $this->lastError(), $this->lastErrno(), 'BEGIN', $fname );
1074 }
1075 }
1076
1077 /**
1078 * End a transaction
1079 * @param string $fname
1080 */
1081 protected function doCommit( $fname = __METHOD__ ) {
1082 if ( !sqlsrv_commit( $this->conn ) ) {
1083 $this->reportQueryError( $this->lastError(), $this->lastErrno(), 'COMMIT', $fname );
1084 }
1085 }
1086
1087 /**
1088 * Rollback a transaction.
1089 * No-op on non-transactional databases.
1090 * @param string $fname
1091 */
1092 protected function doRollback( $fname = __METHOD__ ) {
1093 if ( !sqlsrv_rollback( $this->conn ) ) {
1094 $this->queryLogger->error(
1095 "{fname}\t{db_server}\t{errno}\t{error}\t",
1096 $this->getLogContext( [
1097 'errno' => $this->lastErrno(),
1098 'error' => $this->lastError(),
1099 'fname' => $fname,
1100 'trace' => ( new RuntimeException() )->getTraceAsString()
1101 ] )
1102 );
1103 }
1104 }
1105
1106 /**
1107 * @param string $s
1108 * @return string
1109 */
1110 public function strencode( $s ) {
1111 // Should not be called by us
1112 return str_replace( "'", "''", $s );
1113 }
1114
1115 /**
1116 * @param string|int|null|bool|Blob $s
1117 * @return string|int
1118 */
1119 public function addQuotes( $s ) {
1120 if ( $s instanceof MssqlBlob ) {
1121 return $s->fetch();
1122 } elseif ( $s instanceof Blob ) {
1123 // this shouldn't really ever be called, but it's here if needed
1124 // (and will quite possibly make the SQL error out)
1125 $blob = new MssqlBlob( $s->fetch() );
1126 return $blob->fetch();
1127 } else {
1128 if ( is_bool( $s ) ) {
1129 $s = $s ? 1 : 0;
1130 }
1131 return parent::addQuotes( $s );
1132 }
1133 }
1134
1135 /**
1136 * @param string $s
1137 * @return string
1138 */
1139 public function addIdentifierQuotes( $s ) {
1140 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1141 return '[' . $s . ']';
1142 }
1143
1144 /**
1145 * @param string $name
1146 * @return bool
1147 */
1148 public function isQuotedIdentifier( $name ) {
1149 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1150 }
1151
1152 /**
1153 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1154 *
1155 * @param string $s
1156 * @param string $escapeChar
1157 * @return string
1158 */
1159 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1160 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1161 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1162 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1163 $s );
1164 }
1165
1166 protected function doSelectDomain( DatabaseDomain $domain ) {
1167 if ( $domain->getSchema() !== null ) {
1168 throw new DBExpectedError( $this, __CLASS__ . ": domain schemas are not supported." );
1169 }
1170
1171 $database = $domain->getDatabase();
1172 if ( $database !== $this->getDBname() ) {
1173 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
1174 list( $res, $err, $errno ) =
1175 $this->executeQuery( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
1176
1177 if ( $res === false ) {
1178 $this->reportQueryError( $err, $errno, $sql, __METHOD__ );
1179 return false; // unreachable
1180 }
1181 }
1182 // Update that domain fields on success (no exception thrown)
1183 $this->currentDomain = $domain;
1184
1185 return true;
1186 }
1187
1188 /**
1189 * @param array $options An associative array of options to be turned into
1190 * an SQL query, valid keys are listed in the function.
1191 * @return array
1192 */
1193 public function makeSelectOptions( $options ) {
1194 $tailOpts = '';
1195 $startOpts = '';
1196
1197 $noKeyOptions = [];
1198 foreach ( $options as $key => $option ) {
1199 if ( is_numeric( $key ) ) {
1200 $noKeyOptions[$option] = true;
1201 }
1202 }
1203
1204 $tailOpts .= $this->makeGroupByWithHaving( $options );
1205
1206 $tailOpts .= $this->makeOrderBy( $options );
1207
1208 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1209 $startOpts .= 'DISTINCT';
1210 }
1211
1212 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1213 // used in group concat field emulation
1214 $tailOpts .= " FOR XML PATH('')";
1215 }
1216
1217 // we want this to be compatible with the output of parent::makeSelectOptions()
1218 return [ $startOpts, '', $tailOpts, '', '' ];
1219 }
1220
1221 public function getType() {
1222 return 'mssql';
1223 }
1224
1225 /**
1226 * @param array $stringList
1227 * @return string
1228 */
1229 public function buildConcat( $stringList ) {
1230 return implode( ' + ', $stringList );
1231 }
1232
1233 /**
1234 * Build a GROUP_CONCAT or equivalent statement for a query.
1235 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1236 *
1237 * This is useful for combining a field for several rows into a single string.
1238 * NULL values will not appear in the output, duplicated values will appear,
1239 * and the resulting delimiter-separated values have no defined sort order.
1240 * Code using the results may need to use the PHP unique() or sort() methods.
1241 *
1242 * @param string $delim Glue to bind the results together
1243 * @param string|array $table Table name
1244 * @param string $field Field name
1245 * @param string|array $conds Conditions
1246 * @param string|array $join_conds Join conditions
1247 * @return string SQL text
1248 * @since 1.23
1249 */
1250 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1251 $join_conds = []
1252 ) {
1253 $gcsq = 'gcsq_' . $this->subqueryId;
1254 $this->subqueryId++;
1255
1256 $delimLen = strlen( $delim );
1257 $fld = "{$field} + {$this->addQuotes( $delim )}";
1258 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1259 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1260 . ") {$gcsq} ({$field}))";
1261
1262 return $sql;
1263 }
1264
1265 public function buildSubstring( $input, $startPosition, $length = null ) {
1266 $this->assertBuildSubstringParams( $startPosition, $length );
1267 if ( $length === null ) {
1268 /**
1269 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1270 * length returned use the default maximum size of text.
1271 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1272 */
1273 $length = 2147483647;
1274 }
1275 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1276 }
1277
1278 /**
1279 * Returns an associative array for fields that are of type varbinary, binary, or image
1280 * $table can be either a raw table name or passed through tableName() first
1281 * @param string $table
1282 * @return array
1283 */
1284 private function getBinaryColumns( $table ) {
1285 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1286 $tableRaw = array_pop( $tableRawArr );
1287
1288 if ( $this->binaryColumnCache === null ) {
1289 $this->populateColumnCaches();
1290 }
1291
1292 return $this->binaryColumnCache[$tableRaw] ?? [];
1293 }
1294
1295 /**
1296 * @param string $table
1297 * @return array
1298 */
1299 private function getBitColumns( $table ) {
1300 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1301 $tableRaw = array_pop( $tableRawArr );
1302
1303 if ( $this->bitColumnCache === null ) {
1304 $this->populateColumnCaches();
1305 }
1306
1307 return $this->bitColumnCache[$tableRaw] ?? [];
1308 }
1309
1310 private function populateColumnCaches() {
1311 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1312 [
1313 'TABLE_CATALOG' => $this->getDBname(),
1314 'TABLE_SCHEMA' => $this->dbSchema(),
1315 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1316 ] );
1317
1318 $this->binaryColumnCache = [];
1319 $this->bitColumnCache = [];
1320 foreach ( $res as $row ) {
1321 if ( $row->DATA_TYPE == 'bit' ) {
1322 $this->bitColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1323 } else {
1324 $this->binaryColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1325 }
1326 }
1327 }
1328
1329 /**
1330 * @param string $name
1331 * @param string $format One of "quoted" (default), "raw", or "split".
1332 * @return string|array When the requested $format is "split", a list of database, schema, and
1333 * table name is returned. Database and schema can be `false`.
1334 */
1335 function tableName( $name, $format = 'quoted' ) {
1336 # Replace reserved words with better ones
1337 switch ( $name ) {
1338 case 'user':
1339 return $this->realTableName( 'mwuser', $format );
1340 default:
1341 return $this->realTableName( $name, $format );
1342 }
1343 }
1344
1345 /**
1346 * call this instead of tableName() in the updater when renaming tables
1347 * @param string $name
1348 * @param string $format One of "quoted" (default), "raw", or "split".
1349 * @return string|array When the requested $format is "split", a list of database, schema, and
1350 * table name is returned. Database and schema can be `false`.
1351 * @private
1352 */
1353 function realTableName( $name, $format = 'quoted' ) {
1354 $table = parent::tableName( $name, $format );
1355 if ( $format == 'split' ) {
1356 // Used internally, we want the schema split off from the table name and returned
1357 // as a list with 3 elements (database, schema, table)
1358 return array_pad( explode( '.', $table, 3 ), -3, false );
1359 }
1360 return $table;
1361 }
1362
1363 /**
1364 * Delete a table
1365 * @param string $tableName
1366 * @param string $fName
1367 * @return bool|IResultWrapper
1368 * @since 1.18
1369 */
1370 public function dropTable( $tableName, $fName = __METHOD__ ) {
1371 if ( !$this->tableExists( $tableName, $fName ) ) {
1372 return false;
1373 }
1374
1375 // parent function incorrectly appends CASCADE, which we don't want
1376 $sql = "DROP TABLE " . $this->tableName( $tableName );
1377
1378 return $this->query( $sql, $fName );
1379 }
1380
1381 /**
1382 * Called in the installer and updater.
1383 * Probably doesn't need to be called anywhere else in the codebase.
1384 * @param bool|null $value
1385 * @return bool|null
1386 */
1387 public function prepareStatements( $value = null ) {
1388 $old = $this->prepareStatements;
1389 if ( $value !== null ) {
1390 $this->prepareStatements = $value;
1391 }
1392
1393 return $old;
1394 }
1395
1396 /**
1397 * Called in the installer and updater.
1398 * Probably doesn't need to be called anywhere else in the codebase.
1399 * @param bool|null $value
1400 * @return bool|null
1401 */
1402 public function scrollableCursor( $value = null ) {
1403 $old = $this->scrollableCursor;
1404 if ( $value !== null ) {
1405 $this->scrollableCursor = $value;
1406 }
1407
1408 return $old;
1409 }
1410
1411 public function buildStringCast( $field ) {
1412 return "CAST( $field AS NVARCHAR )";
1413 }
1414
1415 public static function getAttributes() {
1416 return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];
1417 }
1418 }
1419
1420 /**
1421 * @deprecated since 1.29
1422 */
1423 class_alias( DatabaseMssql::class, 'DatabaseMssql' );