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