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