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