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