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