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