Merge "cleanupTitles: Don't add 'Broken/' prefix if the title is valid without it"
[lhc/web/wiklou.git] / includes / libs / rdbms / database / DatabaseMysqlBase.php
1 <?php
2 /**
3 * This is the MySQL 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 */
23 namespace Wikimedia\Rdbms;
24
25 use DateTime;
26 use DateTimeZone;
27 use MediaWiki;
28 use InvalidArgumentException;
29 use Exception;
30 use stdClass;
31
32 /**
33 * Database abstraction object for MySQL.
34 * Defines methods independent on used MySQL extension.
35 *
36 * @ingroup Database
37 * @since 1.22
38 * @see Database
39 */
40 abstract class DatabaseMysqlBase extends Database {
41 /** @var MysqlMasterPos */
42 protected $lastKnownReplicaPos;
43 /** @var string Method to detect replica DB lag */
44 protected $lagDetectionMethod;
45 /** @var array Method to detect replica DB lag */
46 protected $lagDetectionOptions = [];
47 /** @var bool bool Whether to use GTID methods */
48 protected $useGTIDs = false;
49 /** @var string|null */
50 protected $sslKeyPath;
51 /** @var string|null */
52 protected $sslCertPath;
53 /** @var string|null */
54 protected $sslCAFile;
55 /** @var string|null */
56 protected $sslCAPath;
57 /** @var string[]|null */
58 protected $sslCiphers;
59 /** @var string sql_mode value to send on connection */
60 protected $sqlMode;
61 /** @var bool Use experimental UTF-8 transmission encoding */
62 protected $utf8Mode;
63
64 /** @var string|null */
65 private $serverVersion = null;
66 /** @var bool|null */
67 private $insertSelectIsSafe = null;
68
69 /**
70 * Additional $params include:
71 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
72 * pt-heartbeat assumes the table is at heartbeat.heartbeat
73 * and uses UTC timestamps in the heartbeat.ts column.
74 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
75 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
76 * the default behavior. Normally, the heartbeat row with the server
77 * ID of this server's master will be used. Set the "conds" field to
78 * override the query conditions, e.g. ['shard' => 's1'].
79 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
80 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
81 * - sslKeyPath : path to key file [default: null]
82 * - sslCertPath : path to certificate file [default: null]
83 * - sslCAFile: path to a single certificate authority PEM file [default: null]
84 * - sslCAPath : parth to certificate authority PEM directory [default: null]
85 * - sslCiphers : array list of allowable ciphers [default: null]
86 * @param array $params
87 */
88 function __construct( array $params ) {
89 $this->lagDetectionMethod = isset( $params['lagDetectionMethod'] )
90 ? $params['lagDetectionMethod']
91 : 'Seconds_Behind_Master';
92 $this->lagDetectionOptions = isset( $params['lagDetectionOptions'] )
93 ? $params['lagDetectionOptions']
94 : [];
95 $this->useGTIDs = !empty( $params['useGTIDs' ] );
96 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
97 $var = "ssl{$name}";
98 if ( isset( $params[$var] ) ) {
99 $this->$var = $params[$var];
100 }
101 }
102 $this->sqlMode = isset( $params['sqlMode'] ) ? $params['sqlMode'] : '';
103 $this->utf8Mode = !empty( $params['utf8Mode'] );
104 $this->insertSelectIsSafe = isset( $params['insertSelectIsSafe'] )
105 ? (bool)$params['insertSelectIsSafe'] : null;
106
107 parent::__construct( $params );
108 }
109
110 /**
111 * @return string
112 */
113 public function getType() {
114 return 'mysql';
115 }
116
117 /**
118 * @param string $server
119 * @param string $user
120 * @param string $password
121 * @param string $dbName
122 * @throws Exception|DBConnectionError
123 * @return bool
124 */
125 public function open( $server, $user, $password, $dbName ) {
126 # Close/unset connection handle
127 $this->close();
128
129 $this->mServer = $server;
130 $this->mUser = $user;
131 $this->mPassword = $password;
132 $this->mDBname = $dbName;
133
134 $this->installErrorHandler();
135 try {
136 $this->mConn = $this->mysqlConnect( $this->mServer );
137 } catch ( Exception $ex ) {
138 $this->restoreErrorHandler();
139 throw $ex;
140 }
141 $error = $this->restoreErrorHandler();
142
143 # Always log connection errors
144 if ( !$this->mConn ) {
145 if ( !$error ) {
146 $error = $this->lastError();
147 }
148 $this->connLogger->error(
149 "Error connecting to {db_server}: {error}",
150 $this->getLogContext( [
151 'method' => __METHOD__,
152 'error' => $error,
153 ] )
154 );
155 $this->connLogger->debug( "DB connection error\n" .
156 "Server: $server, User: $user, Password: " .
157 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
158
159 $this->reportConnectionError( $error );
160 }
161
162 if ( $dbName != '' ) {
163 MediaWiki\suppressWarnings();
164 $success = $this->selectDB( $dbName );
165 MediaWiki\restoreWarnings();
166 if ( !$success ) {
167 $this->queryLogger->error(
168 "Error selecting database {db_name} on server {db_server}",
169 $this->getLogContext( [
170 'method' => __METHOD__,
171 ] )
172 );
173 $this->queryLogger->debug(
174 "Error selecting database $dbName on server {$this->mServer}" );
175
176 $this->reportConnectionError( "Error selecting database $dbName" );
177 }
178 }
179
180 // Tell the server what we're communicating with
181 if ( !$this->connectInitCharset() ) {
182 $this->reportConnectionError( "Error setting character set" );
183 }
184
185 // Abstract over any insane MySQL defaults
186 $set = [ 'group_concat_max_len = 262144' ];
187 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
188 if ( is_string( $this->sqlMode ) ) {
189 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode );
190 }
191 // Set any custom settings defined by site config
192 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
193 foreach ( $this->mSessionVars as $var => $val ) {
194 // Escape strings but not numbers to avoid MySQL complaining
195 if ( !is_int( $val ) && !is_float( $val ) ) {
196 $val = $this->addQuotes( $val );
197 }
198 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
199 }
200
201 if ( $set ) {
202 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
203 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
204 if ( !$success ) {
205 $this->queryLogger->error(
206 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
207 $this->getLogContext( [
208 'method' => __METHOD__,
209 ] )
210 );
211 $this->reportConnectionError(
212 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
213 }
214 }
215
216 $this->mOpened = true;
217
218 return true;
219 }
220
221 /**
222 * Set the character set information right after connection
223 * @return bool
224 */
225 protected function connectInitCharset() {
226 if ( $this->utf8Mode ) {
227 // Tell the server we're communicating with it in UTF-8.
228 // This may engage various charset conversions.
229 return $this->mysqlSetCharset( 'utf8' );
230 } else {
231 return $this->mysqlSetCharset( 'binary' );
232 }
233 }
234
235 /**
236 * Open a connection to a MySQL server
237 *
238 * @param string $realServer
239 * @return mixed Raw connection
240 * @throws DBConnectionError
241 */
242 abstract protected function mysqlConnect( $realServer );
243
244 /**
245 * Set the character set of the MySQL link
246 *
247 * @param string $charset
248 * @return bool
249 */
250 abstract protected function mysqlSetCharset( $charset );
251
252 /**
253 * @param ResultWrapper|resource $res
254 * @throws DBUnexpectedError
255 */
256 public function freeResult( $res ) {
257 if ( $res instanceof ResultWrapper ) {
258 $res = $res->result;
259 }
260 MediaWiki\suppressWarnings();
261 $ok = $this->mysqlFreeResult( $res );
262 MediaWiki\restoreWarnings();
263 if ( !$ok ) {
264 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
265 }
266 }
267
268 /**
269 * Free result memory
270 *
271 * @param resource $res Raw result
272 * @return bool
273 */
274 abstract protected function mysqlFreeResult( $res );
275
276 /**
277 * @param ResultWrapper|resource $res
278 * @return stdClass|bool
279 * @throws DBUnexpectedError
280 */
281 public function fetchObject( $res ) {
282 if ( $res instanceof ResultWrapper ) {
283 $res = $res->result;
284 }
285 MediaWiki\suppressWarnings();
286 $row = $this->mysqlFetchObject( $res );
287 MediaWiki\restoreWarnings();
288
289 $errno = $this->lastErrno();
290 // Unfortunately, mysql_fetch_object does not reset the last errno.
291 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
292 // these are the only errors mysql_fetch_object can cause.
293 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
294 if ( $errno == 2000 || $errno == 2013 ) {
295 throw new DBUnexpectedError(
296 $this,
297 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
298 );
299 }
300
301 return $row;
302 }
303
304 /**
305 * Fetch a result row as an object
306 *
307 * @param resource $res Raw result
308 * @return stdClass
309 */
310 abstract protected function mysqlFetchObject( $res );
311
312 /**
313 * @param ResultWrapper|resource $res
314 * @return array|bool
315 * @throws DBUnexpectedError
316 */
317 public function fetchRow( $res ) {
318 if ( $res instanceof ResultWrapper ) {
319 $res = $res->result;
320 }
321 MediaWiki\suppressWarnings();
322 $row = $this->mysqlFetchArray( $res );
323 MediaWiki\restoreWarnings();
324
325 $errno = $this->lastErrno();
326 // Unfortunately, mysql_fetch_array does not reset the last errno.
327 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
328 // these are the only errors mysql_fetch_array can cause.
329 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
330 if ( $errno == 2000 || $errno == 2013 ) {
331 throw new DBUnexpectedError(
332 $this,
333 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
334 );
335 }
336
337 return $row;
338 }
339
340 /**
341 * Fetch a result row as an associative and numeric array
342 *
343 * @param resource $res Raw result
344 * @return array
345 */
346 abstract protected function mysqlFetchArray( $res );
347
348 /**
349 * @throws DBUnexpectedError
350 * @param ResultWrapper|resource $res
351 * @return int
352 */
353 function numRows( $res ) {
354 if ( $res instanceof ResultWrapper ) {
355 $res = $res->result;
356 }
357 MediaWiki\suppressWarnings();
358 $n = $this->mysqlNumRows( $res );
359 MediaWiki\restoreWarnings();
360
361 // Unfortunately, mysql_num_rows does not reset the last errno.
362 // We are not checking for any errors here, since
363 // these are no errors mysql_num_rows can cause.
364 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
365 // See https://phabricator.wikimedia.org/T44430
366 return $n;
367 }
368
369 /**
370 * Get number of rows in result
371 *
372 * @param resource $res Raw result
373 * @return int
374 */
375 abstract protected function mysqlNumRows( $res );
376
377 /**
378 * @param ResultWrapper|resource $res
379 * @return int
380 */
381 public function numFields( $res ) {
382 if ( $res instanceof ResultWrapper ) {
383 $res = $res->result;
384 }
385
386 return $this->mysqlNumFields( $res );
387 }
388
389 /**
390 * Get number of fields in result
391 *
392 * @param resource $res Raw result
393 * @return int
394 */
395 abstract protected function mysqlNumFields( $res );
396
397 /**
398 * @param ResultWrapper|resource $res
399 * @param int $n
400 * @return string
401 */
402 public function fieldName( $res, $n ) {
403 if ( $res instanceof ResultWrapper ) {
404 $res = $res->result;
405 }
406
407 return $this->mysqlFieldName( $res, $n );
408 }
409
410 /**
411 * Get the name of the specified field in a result
412 *
413 * @param ResultWrapper|resource $res
414 * @param int $n
415 * @return string
416 */
417 abstract protected function mysqlFieldName( $res, $n );
418
419 /**
420 * mysql_field_type() wrapper
421 * @param ResultWrapper|resource $res
422 * @param int $n
423 * @return string
424 */
425 public function fieldType( $res, $n ) {
426 if ( $res instanceof ResultWrapper ) {
427 $res = $res->result;
428 }
429
430 return $this->mysqlFieldType( $res, $n );
431 }
432
433 /**
434 * Get the type of the specified field in a result
435 *
436 * @param ResultWrapper|resource $res
437 * @param int $n
438 * @return string
439 */
440 abstract protected function mysqlFieldType( $res, $n );
441
442 /**
443 * @param ResultWrapper|resource $res
444 * @param int $row
445 * @return bool
446 */
447 public function dataSeek( $res, $row ) {
448 if ( $res instanceof ResultWrapper ) {
449 $res = $res->result;
450 }
451
452 return $this->mysqlDataSeek( $res, $row );
453 }
454
455 /**
456 * Move internal result pointer
457 *
458 * @param ResultWrapper|resource $res
459 * @param int $row
460 * @return bool
461 */
462 abstract protected function mysqlDataSeek( $res, $row );
463
464 /**
465 * @return string
466 */
467 public function lastError() {
468 if ( $this->mConn ) {
469 # Even if it's non-zero, it can still be invalid
470 MediaWiki\suppressWarnings();
471 $error = $this->mysqlError( $this->mConn );
472 if ( !$error ) {
473 $error = $this->mysqlError();
474 }
475 MediaWiki\restoreWarnings();
476 } else {
477 $error = $this->mysqlError();
478 }
479 if ( $error ) {
480 $error .= ' (' . $this->mServer . ')';
481 }
482
483 return $error;
484 }
485
486 /**
487 * Returns the text of the error message from previous MySQL operation
488 *
489 * @param resource $conn Raw connection
490 * @return string
491 */
492 abstract protected function mysqlError( $conn = null );
493
494 protected function wasQueryTimeout( $error, $errno ) {
495 return $errno == 2062;
496 }
497
498 /**
499 * @param string $table
500 * @param array $uniqueIndexes
501 * @param array $rows
502 * @param string $fname
503 * @return ResultWrapper
504 */
505 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
506 return $this->nativeReplace( $table, $rows, $fname );
507 }
508
509 protected function nativeInsertSelect(
510 $destTable, $srcTable, $varMap, $conds,
511 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
512 ) {
513 if ( $this->insertSelectIsSafe === null ) {
514 // In MySQL, an INSERT SELECT is only replication safe with row-based
515 // replication or if innodb_autoinc_lock_mode is 0. When those
516 // conditions aren't met, use non-native mode.
517 // While we could try to determine if the insert is safe anyway by
518 // checking if the target table has an auto-increment column that
519 // isn't set in $varMap, that seems unlikely to be worth the extra
520 // complexity.
521 $row = $this->selectRow(
522 false,
523 [
524 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
525 'binlog_format' => '@@binlog_format',
526 ],
527 [],
528 __METHOD__
529 );
530 $this->insertSelectIsSafe = $row->binlog_format === 'ROW' ||
531 (int)$row->innodb_autoinc_lock_mode === 0;
532 }
533
534 if ( !$this->insertSelectIsSafe ) {
535 return $this->nonNativeInsertSelect(
536 $destTable,
537 $srcTable,
538 $varMap,
539 $conds,
540 $fname,
541 $insertOptions,
542 $selectOptions,
543 $selectJoinConds
544 );
545 } else {
546 return parent::nativeInsertSelect(
547 $destTable,
548 $srcTable,
549 $varMap,
550 $conds,
551 $fname,
552 $insertOptions,
553 $selectOptions,
554 $selectJoinConds
555 );
556 }
557 }
558
559 /**
560 * Estimate rows in dataset
561 * Returns estimated count, based on EXPLAIN output
562 * Takes same arguments as Database::select()
563 *
564 * @param string|array $table
565 * @param string|array $vars
566 * @param string|array $conds
567 * @param string $fname
568 * @param string|array $options
569 * @return bool|int
570 */
571 public function estimateRowCount( $table, $vars = '*', $conds = '',
572 $fname = __METHOD__, $options = []
573 ) {
574 $options['EXPLAIN'] = true;
575 $res = $this->select( $table, $vars, $conds, $fname, $options );
576 if ( $res === false ) {
577 return false;
578 }
579 if ( !$this->numRows( $res ) ) {
580 return 0;
581 }
582
583 $rows = 1;
584 foreach ( $res as $plan ) {
585 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
586 }
587
588 return (int)$rows;
589 }
590
591 public function tableExists( $table, $fname = __METHOD__ ) {
592 // Split database and table into proper variables as Database::tableName() returns
593 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
594 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
595 $tableName = "{$prefix}{$table}";
596
597 if ( isset( $this->mSessionTempTables[$tableName] ) ) {
598 return true; // already known to exist and won't show in SHOW TABLES anyway
599 }
600
601 // We can't use buildLike() here, because it specifies an escape character
602 // other than the backslash, which is the only one supported by SHOW TABLES
603 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
604
605 // If the database has been specified (such as for shared tables), use "FROM"
606 if ( $database !== '' ) {
607 $encDatabase = $this->addIdentifierQuotes( $database );
608 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
609 } else {
610 $query = "SHOW TABLES LIKE '$encLike'";
611 }
612
613 return $this->query( $query, $fname )->numRows() > 0;
614 }
615
616 /**
617 * @param string $table
618 * @param string $field
619 * @return bool|MySQLField
620 */
621 public function fieldInfo( $table, $field ) {
622 $table = $this->tableName( $table );
623 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
624 if ( !$res ) {
625 return false;
626 }
627 $n = $this->mysqlNumFields( $res->result );
628 for ( $i = 0; $i < $n; $i++ ) {
629 $meta = $this->mysqlFetchField( $res->result, $i );
630 if ( $field == $meta->name ) {
631 return new MySQLField( $meta );
632 }
633 }
634
635 return false;
636 }
637
638 /**
639 * Get column information from a result
640 *
641 * @param resource $res Raw result
642 * @param int $n
643 * @return stdClass
644 */
645 abstract protected function mysqlFetchField( $res, $n );
646
647 /**
648 * Get information about an index into an object
649 * Returns false if the index does not exist
650 *
651 * @param string $table
652 * @param string $index
653 * @param string $fname
654 * @return bool|array|null False or null on failure
655 */
656 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
657 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
658 # SHOW INDEX should work for 3.x and up:
659 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
660 $table = $this->tableName( $table );
661 $index = $this->indexName( $index );
662
663 $sql = 'SHOW INDEX FROM ' . $table;
664 $res = $this->query( $sql, $fname );
665
666 if ( !$res ) {
667 return null;
668 }
669
670 $result = [];
671
672 foreach ( $res as $row ) {
673 if ( $row->Key_name == $index ) {
674 $result[] = $row;
675 }
676 }
677
678 return empty( $result ) ? false : $result;
679 }
680
681 /**
682 * @param string $s
683 * @return string
684 */
685 public function strencode( $s ) {
686 return $this->mysqlRealEscapeString( $s );
687 }
688
689 /**
690 * @param string $s
691 * @return mixed
692 */
693 abstract protected function mysqlRealEscapeString( $s );
694
695 public function addQuotes( $s ) {
696 if ( is_bool( $s ) ) {
697 // Parent would transform to int, which does not play nice with MySQL type juggling.
698 // When searching for an int in a string column, the strings are cast to int, which
699 // means false would match any string not starting with a number.
700 $s = (string)(int)$s;
701 }
702 return parent::addQuotes( $s );
703 }
704
705 /**
706 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
707 *
708 * @param string $s
709 * @return string
710 */
711 public function addIdentifierQuotes( $s ) {
712 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
713 // Remove NUL bytes and escape backticks by doubling
714 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
715 }
716
717 /**
718 * @param string $name
719 * @return bool
720 */
721 public function isQuotedIdentifier( $name ) {
722 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
723 }
724
725 public function getLag() {
726 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
727 return $this->getLagFromPtHeartbeat();
728 } else {
729 return $this->getLagFromSlaveStatus();
730 }
731 }
732
733 /**
734 * @return string
735 */
736 protected function getLagDetectionMethod() {
737 return $this->lagDetectionMethod;
738 }
739
740 /**
741 * @return bool|int
742 */
743 protected function getLagFromSlaveStatus() {
744 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
745 $row = $res ? $res->fetchObject() : false;
746 if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
747 return intval( $row->Seconds_Behind_Master );
748 }
749
750 return false;
751 }
752
753 /**
754 * @return bool|float
755 */
756 protected function getLagFromPtHeartbeat() {
757 $options = $this->lagDetectionOptions;
758
759 if ( isset( $options['conds'] ) ) {
760 // Best method for multi-DC setups: use logical channel names
761 $data = $this->getHeartbeatData( $options['conds'] );
762 } else {
763 // Standard method: use master server ID (works with stock pt-heartbeat)
764 $masterInfo = $this->getMasterServerInfo();
765 if ( !$masterInfo ) {
766 $this->queryLogger->error(
767 "Unable to query master of {db_server} for server ID",
768 $this->getLogContext( [
769 'method' => __METHOD__
770 ] )
771 );
772
773 return false; // could not get master server ID
774 }
775
776 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
777 $data = $this->getHeartbeatData( $conds );
778 }
779
780 list( $time, $nowUnix ) = $data;
781 if ( $time !== null ) {
782 // @time is in ISO format like "2015-09-25T16:48:10.000510"
783 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
784 $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
785
786 return max( $nowUnix - $timeUnix, 0.0 );
787 }
788
789 $this->queryLogger->error(
790 "Unable to find pt-heartbeat row for {db_server}",
791 $this->getLogContext( [
792 'method' => __METHOD__
793 ] )
794 );
795
796 return false;
797 }
798
799 protected function getMasterServerInfo() {
800 $cache = $this->srvCache;
801 $key = $cache->makeGlobalKey(
802 'mysql',
803 'master-info',
804 // Using one key for all cluster replica DBs is preferable
805 $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
806 );
807
808 return $cache->getWithSetCallback(
809 $key,
810 $cache::TTL_INDEFINITE,
811 function () use ( $cache, $key ) {
812 // Get and leave a lock key in place for a short period
813 if ( !$cache->lock( $key, 0, 10 ) ) {
814 return false; // avoid master connection spike slams
815 }
816
817 $conn = $this->getLazyMasterHandle();
818 if ( !$conn ) {
819 return false; // something is misconfigured
820 }
821
822 // Connect to and query the master; catch errors to avoid outages
823 try {
824 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__ );
825 $row = $res ? $res->fetchObject() : false;
826 $id = $row ? (int)$row->id : 0;
827 } catch ( DBError $e ) {
828 $id = 0;
829 }
830
831 // Cache the ID if it was retrieved
832 return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
833 }
834 );
835 }
836
837 /**
838 * @param array $conds WHERE clause conditions to find a row
839 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
840 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
841 */
842 protected function getHeartbeatData( array $conds ) {
843 // Query time and trip time are not counted
844 $nowUnix = microtime( true );
845 // Do not bother starting implicit transactions here
846 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
847 try {
848 $whereSQL = $this->makeList( $conds, self::LIST_AND );
849 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
850 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
851 // percision field is not supported in MySQL <= 5.5.
852 $res = $this->query(
853 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
854 );
855 $row = $res ? $res->fetchObject() : false;
856 } finally {
857 $this->restoreFlags();
858 }
859
860 return [ $row ? $row->ts : null, $nowUnix ];
861 }
862
863 protected function getApproximateLagStatus() {
864 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
865 // Disable caching since this is fast enough and we don't wan't
866 // to be *too* pessimistic by having both the cache TTL and the
867 // pt-heartbeat interval count as lag in getSessionLagStatus()
868 return parent::getApproximateLagStatus();
869 }
870
871 $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
872 $approxLag = $this->srvCache->get( $key );
873 if ( !$approxLag ) {
874 $approxLag = parent::getApproximateLagStatus();
875 $this->srvCache->set( $key, $approxLag, 1 );
876 }
877
878 return $approxLag;
879 }
880
881 public function masterPosWait( DBMasterPos $pos, $timeout ) {
882 if ( !( $pos instanceof MySQLMasterPos ) ) {
883 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
884 }
885
886 if ( $this->getLBInfo( 'is static' ) === true ) {
887 return 0; // this is a copy of a read-only dataset with no master DB
888 } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
889 return 0; // already reached this point for sure
890 }
891
892 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
893 if ( $this->useGTIDs && $pos->gtids ) {
894 // Wait on the GTID set (MariaDB only)
895 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids ) );
896 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
897 } else {
898 // Wait on the binlog coordinates
899 $encFile = $this->addQuotes( $pos->file );
900 $encPos = intval( $pos->pos );
901 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
902 }
903
904 $row = $res ? $this->fetchRow( $res ) : false;
905 if ( !$row ) {
906 throw new DBExpectedError( $this,
907 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
908 }
909
910 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
911 $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
912 if ( $status === null ) {
913 // T126436: jobs programmed to wait on master positions might be referencing binlogs
914 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
915 // to detect this and treat the replica DB as having reached the position; a proper master
916 // switchover already requires that the new master be caught up before the switch.
917 $replicationPos = $this->getReplicaPos();
918 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
919 $this->lastKnownReplicaPos = $replicationPos;
920 $status = 0;
921 }
922 } elseif ( $status >= 0 ) {
923 // Remember that this position was reached to save queries next time
924 $this->lastKnownReplicaPos = $pos;
925 }
926
927 return $status;
928 }
929
930 /**
931 * Get the position of the master from SHOW SLAVE STATUS
932 *
933 * @return MySQLMasterPos|bool
934 */
935 public function getReplicaPos() {
936 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
937 $row = $this->fetchObject( $res );
938
939 if ( $row ) {
940 $pos = isset( $row->Exec_master_log_pos )
941 ? $row->Exec_master_log_pos
942 : $row->Exec_Master_Log_Pos;
943 // Also fetch the last-applied GTID set (MariaDB)
944 if ( $this->useGTIDs ) {
945 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__ );
946 $gtidRow = $this->fetchObject( $res );
947 $gtidSet = $gtidRow ? $gtidRow->Value : '';
948 } else {
949 $gtidSet = '';
950 }
951
952 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos, $gtidSet );
953 } else {
954 return false;
955 }
956 }
957
958 /**
959 * Get the position of the master from SHOW MASTER STATUS
960 *
961 * @return MySQLMasterPos|bool
962 */
963 public function getMasterPos() {
964 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__ );
965 $row = $this->fetchObject( $res );
966
967 if ( $row ) {
968 // Also fetch the last-written GTID set (MariaDB)
969 if ( $this->useGTIDs ) {
970 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__ );
971 $gtidRow = $this->fetchObject( $res );
972 $gtidSet = $gtidRow ? $gtidRow->Value : '';
973 } else {
974 $gtidSet = '';
975 }
976
977 return new MySQLMasterPos( $row->File, $row->Position, $gtidSet );
978 } else {
979 return false;
980 }
981 }
982
983 public function serverIsReadOnly() {
984 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__ );
985 $row = $this->fetchObject( $res );
986
987 return $row ? ( strtolower( $row->Value ) === 'on' ) : false;
988 }
989
990 /**
991 * @param string $index
992 * @return string
993 */
994 function useIndexClause( $index ) {
995 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
996 }
997
998 /**
999 * @param string $index
1000 * @return string
1001 */
1002 function ignoreIndexClause( $index ) {
1003 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1004 }
1005
1006 /**
1007 * @return string
1008 */
1009 function lowPriorityOption() {
1010 return 'LOW_PRIORITY';
1011 }
1012
1013 /**
1014 * @return string
1015 */
1016 public function getSoftwareLink() {
1017 // MariaDB includes its name in its version string; this is how MariaDB's version of
1018 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1019 // in libmysql/libmysql.c).
1020 $version = $this->getServerVersion();
1021 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
1022 return '[{{int:version-db-mariadb-url}} MariaDB]';
1023 }
1024
1025 // Percona Server's version suffix is not very distinctive, and @@version_comment
1026 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1027 // (Even Percona's version of mysql doesn't try to make the distinction.)
1028 return '[{{int:version-db-mysql-url}} MySQL]';
1029 }
1030
1031 /**
1032 * @return string
1033 */
1034 public function getServerVersion() {
1035 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1036 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1037 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1038 if ( $this->serverVersion === null ) {
1039 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
1040 }
1041 return $this->serverVersion;
1042 }
1043
1044 /**
1045 * @param array $options
1046 */
1047 public function setSessionOptions( array $options ) {
1048 if ( isset( $options['connTimeout'] ) ) {
1049 $timeout = (int)$options['connTimeout'];
1050 $this->query( "SET net_read_timeout=$timeout" );
1051 $this->query( "SET net_write_timeout=$timeout" );
1052 }
1053 }
1054
1055 /**
1056 * @param string &$sql
1057 * @param string &$newLine
1058 * @return bool
1059 */
1060 public function streamStatementEnd( &$sql, &$newLine ) {
1061 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1062 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1063 $this->delimiter = $m[1];
1064 $newLine = '';
1065 }
1066
1067 return parent::streamStatementEnd( $sql, $newLine );
1068 }
1069
1070 /**
1071 * Check to see if a named lock is available. This is non-blocking.
1072 *
1073 * @param string $lockName Name of lock to poll
1074 * @param string $method Name of method calling us
1075 * @return bool
1076 * @since 1.20
1077 */
1078 public function lockIsFree( $lockName, $method ) {
1079 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1080 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1081 $row = $this->fetchObject( $result );
1082
1083 return ( $row->lockstatus == 1 );
1084 }
1085
1086 /**
1087 * @param string $lockName
1088 * @param string $method
1089 * @param int $timeout
1090 * @return bool
1091 */
1092 public function lock( $lockName, $method, $timeout = 5 ) {
1093 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1094 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1095 $row = $this->fetchObject( $result );
1096
1097 if ( $row->lockstatus == 1 ) {
1098 parent::lock( $lockName, $method, $timeout ); // record
1099 return true;
1100 }
1101
1102 $this->queryLogger->info( __METHOD__ . " failed to acquire lock '{lockname}'",
1103 [ 'lockname' => $lockName ] );
1104
1105 return false;
1106 }
1107
1108 /**
1109 * FROM MYSQL DOCS:
1110 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1111 * @param string $lockName
1112 * @param string $method
1113 * @return bool
1114 */
1115 public function unlock( $lockName, $method ) {
1116 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1117 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1118 $row = $this->fetchObject( $result );
1119
1120 if ( $row->lockstatus == 1 ) {
1121 parent::unlock( $lockName, $method ); // record
1122 return true;
1123 }
1124
1125 $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
1126
1127 return false;
1128 }
1129
1130 private function makeLockName( $lockName ) {
1131 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1132 // Newer version enforce a 64 char length limit.
1133 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1134 }
1135
1136 public function namedLocksEnqueue() {
1137 return true;
1138 }
1139
1140 public function tableLocksHaveTransactionScope() {
1141 return false; // tied to TCP connection
1142 }
1143
1144 protected function doLockTables( array $read, array $write, $method ) {
1145 $items = [];
1146 foreach ( $write as $table ) {
1147 $items[] = $this->tableName( $table ) . ' WRITE';
1148 }
1149 foreach ( $read as $table ) {
1150 $items[] = $this->tableName( $table ) . ' READ';
1151 }
1152
1153 $sql = "LOCK TABLES " . implode( ',', $items );
1154 $this->query( $sql, $method );
1155
1156 return true;
1157 }
1158
1159 protected function doUnlockTables( $method ) {
1160 $this->query( "UNLOCK TABLES", $method );
1161
1162 return true;
1163 }
1164
1165 /**
1166 * @param bool $value
1167 */
1168 public function setBigSelects( $value = true ) {
1169 if ( $value === 'default' ) {
1170 if ( $this->mDefaultBigSelects === null ) {
1171 # Function hasn't been called before so it must already be set to the default
1172 return;
1173 } else {
1174 $value = $this->mDefaultBigSelects;
1175 }
1176 } elseif ( $this->mDefaultBigSelects === null ) {
1177 $this->mDefaultBigSelects =
1178 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1179 }
1180 $encValue = $value ? '1' : '0';
1181 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
1182 }
1183
1184 /**
1185 * DELETE where the condition is a join. MySql uses multi-table deletes.
1186 * @param string $delTable
1187 * @param string $joinTable
1188 * @param string $delVar
1189 * @param string $joinVar
1190 * @param array|string $conds
1191 * @param bool|string $fname
1192 * @throws DBUnexpectedError
1193 * @return bool|ResultWrapper
1194 */
1195 public function deleteJoin(
1196 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1197 ) {
1198 if ( !$conds ) {
1199 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1200 }
1201
1202 $delTable = $this->tableName( $delTable );
1203 $joinTable = $this->tableName( $joinTable );
1204 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1205
1206 if ( $conds != '*' ) {
1207 $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1208 }
1209
1210 return $this->query( $sql, $fname );
1211 }
1212
1213 /**
1214 * @param string $table
1215 * @param array $rows
1216 * @param array $uniqueIndexes
1217 * @param array $set
1218 * @param string $fname
1219 * @return bool
1220 */
1221 public function upsert( $table, array $rows, array $uniqueIndexes,
1222 array $set, $fname = __METHOD__
1223 ) {
1224 if ( !count( $rows ) ) {
1225 return true; // nothing to do
1226 }
1227
1228 if ( !is_array( reset( $rows ) ) ) {
1229 $rows = [ $rows ];
1230 }
1231
1232 $table = $this->tableName( $table );
1233 $columns = array_keys( $rows[0] );
1234
1235 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1236 $rowTuples = [];
1237 foreach ( $rows as $row ) {
1238 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1239 }
1240 $sql .= implode( ',', $rowTuples );
1241 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
1242
1243 return (bool)$this->query( $sql, $fname );
1244 }
1245
1246 /**
1247 * Determines how long the server has been up
1248 *
1249 * @return int
1250 */
1251 public function getServerUptime() {
1252 $vars = $this->getMysqlStatus( 'Uptime' );
1253
1254 return (int)$vars['Uptime'];
1255 }
1256
1257 /**
1258 * Determines if the last failure was due to a deadlock
1259 *
1260 * @return bool
1261 */
1262 public function wasDeadlock() {
1263 return $this->lastErrno() == 1213;
1264 }
1265
1266 /**
1267 * Determines if the last failure was due to a lock timeout
1268 *
1269 * @return bool
1270 */
1271 public function wasLockTimeout() {
1272 return $this->lastErrno() == 1205;
1273 }
1274
1275 public function wasErrorReissuable() {
1276 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1277 }
1278
1279 /**
1280 * Determines if the last failure was due to the database being read-only.
1281 *
1282 * @return bool
1283 */
1284 public function wasReadOnlyError() {
1285 return $this->lastErrno() == 1223 ||
1286 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1287 }
1288
1289 public function wasConnectionError( $errno ) {
1290 return $errno == 2013 || $errno == 2006;
1291 }
1292
1293 /**
1294 * @param string $oldName
1295 * @param string $newName
1296 * @param bool $temporary
1297 * @param string $fname
1298 * @return bool
1299 */
1300 public function duplicateTableStructure(
1301 $oldName, $newName, $temporary = false, $fname = __METHOD__
1302 ) {
1303 $tmp = $temporary ? 'TEMPORARY ' : '';
1304 $newName = $this->addIdentifierQuotes( $newName );
1305 $oldName = $this->addIdentifierQuotes( $oldName );
1306 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1307
1308 return $this->query( $query, $fname );
1309 }
1310
1311 /**
1312 * List all tables on the database
1313 *
1314 * @param string $prefix Only show tables with this prefix, e.g. mw_
1315 * @param string $fname Calling function name
1316 * @return array
1317 */
1318 public function listTables( $prefix = null, $fname = __METHOD__ ) {
1319 $result = $this->query( "SHOW TABLES", $fname );
1320
1321 $endArray = [];
1322
1323 foreach ( $result as $table ) {
1324 $vars = get_object_vars( $table );
1325 $table = array_pop( $vars );
1326
1327 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1328 $endArray[] = $table;
1329 }
1330 }
1331
1332 return $endArray;
1333 }
1334
1335 /**
1336 * @param string $tableName
1337 * @param string $fName
1338 * @return bool|ResultWrapper
1339 */
1340 public function dropTable( $tableName, $fName = __METHOD__ ) {
1341 if ( !$this->tableExists( $tableName, $fName ) ) {
1342 return false;
1343 }
1344
1345 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1346 }
1347
1348 /**
1349 * Get status information from SHOW STATUS in an associative array
1350 *
1351 * @param string $which
1352 * @return array
1353 */
1354 private function getMysqlStatus( $which = "%" ) {
1355 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1356 $status = [];
1357
1358 foreach ( $res as $row ) {
1359 $status[$row->Variable_name] = $row->Value;
1360 }
1361
1362 return $status;
1363 }
1364
1365 /**
1366 * Lists VIEWs in the database
1367 *
1368 * @param string $prefix Only show VIEWs with this prefix, eg.
1369 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1370 * @param string $fname Name of calling function
1371 * @return array
1372 * @since 1.22
1373 */
1374 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1375 // The name of the column containing the name of the VIEW
1376 $propertyName = 'Tables_in_' . $this->mDBname;
1377
1378 // Query for the VIEWS
1379 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1380 $allViews = [];
1381 foreach ( $res as $row ) {
1382 array_push( $allViews, $row->$propertyName );
1383 }
1384
1385 if ( is_null( $prefix ) || $prefix === '' ) {
1386 return $allViews;
1387 }
1388
1389 $filteredViews = [];
1390 foreach ( $allViews as $viewName ) {
1391 // Does the name of this VIEW start with the table-prefix?
1392 if ( strpos( $viewName, $prefix ) === 0 ) {
1393 array_push( $filteredViews, $viewName );
1394 }
1395 }
1396
1397 return $filteredViews;
1398 }
1399
1400 /**
1401 * Differentiates between a TABLE and a VIEW.
1402 *
1403 * @param string $name Name of the TABLE/VIEW to test
1404 * @param string $prefix
1405 * @return bool
1406 * @since 1.22
1407 */
1408 public function isView( $name, $prefix = null ) {
1409 return in_array( $name, $this->listViews( $prefix ) );
1410 }
1411
1412 /**
1413 * Allows for index remapping in queries where this is not consistent across DBMS
1414 *
1415 * @param string $index
1416 * @return string
1417 */
1418 protected function indexName( $index ) {
1419 /**
1420 * When SQLite indexes were introduced in r45764, it was noted that
1421 * SQLite requires index names to be unique within the whole database,
1422 * not just within a schema. As discussed in CR r45819, to avoid the
1423 * need for a schema change on existing installations, the indexes
1424 * were implicitly mapped from the new names to the old names.
1425 *
1426 * This mapping can be removed if DB patches are introduced to alter
1427 * the relevant tables in existing installations. Note that because
1428 * this index mapping applies to table creation, even new installations
1429 * of MySQL have the old names (except for installations created during
1430 * a period where this mapping was inappropriately removed, see
1431 * T154872).
1432 */
1433 $renamed = [
1434 'ar_usertext_timestamp' => 'usertext_timestamp',
1435 'un_user_id' => 'user_id',
1436 'un_user_ip' => 'user_ip',
1437 ];
1438
1439 if ( isset( $renamed[$index] ) ) {
1440 return $renamed[$index];
1441 } else {
1442 return $index;
1443 }
1444 }
1445 }
1446
1447 class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );