Merge "Improve default behavior for HTMLForm::canDisplayErrors"
[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 getLag() {
603 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
604 return $this->getLagFromPtHeartbeat();
605 } else {
606 return $this->getLagFromSlaveStatus();
607 }
608 }
609
610 /**
611 * @return string
612 */
613 protected function getLagDetectionMethod() {
614 return $this->lagDetectionMethod;
615 }
616
617 /**
618 * @return bool|int
619 */
620 protected function getLagFromSlaveStatus() {
621 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
622 $row = $res ? $res->fetchObject() : false;
623 if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
624 return intval( $row->Seconds_Behind_Master );
625 }
626
627 return false;
628 }
629
630 /**
631 * @return bool|float
632 */
633 protected function getLagFromPtHeartbeat() {
634 $options = $this->lagDetectionOptions;
635
636 if ( isset( $options['conds'] ) ) {
637 // Best method for multi-DC setups: use logical channel names
638 $data = $this->getHeartbeatData( $options['conds'] );
639 } else {
640 // Standard method: use master server ID (works with stock pt-heartbeat)
641 $masterInfo = $this->getMasterServerInfo();
642 if ( !$masterInfo ) {
643 wfLogDBError(
644 "Unable to query master of {db_server} for server ID",
645 $this->getLogContext( [
646 'method' => __METHOD__
647 ] )
648 );
649
650 return false; // could not get master server ID
651 }
652
653 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
654 $data = $this->getHeartbeatData( $conds );
655 }
656
657 list( $time, $nowUnix ) = $data;
658 if ( $time !== null ) {
659 // @time is in ISO format like "2015-09-25T16:48:10.000510"
660 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
661 $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
662
663 return max( $nowUnix - $timeUnix, 0.0 );
664 }
665
666 wfLogDBError(
667 "Unable to find pt-heartbeat row for {db_server}",
668 $this->getLogContext( [
669 'method' => __METHOD__
670 ] )
671 );
672
673 return false;
674 }
675
676 protected function getMasterServerInfo() {
677 $cache = $this->srvCache;
678 $key = $cache->makeGlobalKey(
679 'mysql',
680 'master-info',
681 // Using one key for all cluster slaves is preferable
682 $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
683 );
684
685 return $cache->getWithSetCallback(
686 $key,
687 $cache::TTL_INDEFINITE,
688 function () use ( $cache, $key ) {
689 // Get and leave a lock key in place for a short period
690 if ( !$cache->lock( $key, 0, 10 ) ) {
691 return false; // avoid master connection spike slams
692 }
693
694 $conn = $this->getLazyMasterHandle();
695 if ( !$conn ) {
696 return false; // something is misconfigured
697 }
698
699 // Connect to and query the master; catch errors to avoid outages
700 try {
701 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__ );
702 $row = $res ? $res->fetchObject() : false;
703 $id = $row ? (int)$row->id : 0;
704 } catch ( DBError $e ) {
705 $id = 0;
706 }
707
708 // Cache the ID if it was retrieved
709 return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
710 }
711 );
712 }
713
714 /**
715 * @param array $conds WHERE clause conditions to find a row
716 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
717 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
718 */
719 protected function getHeartbeatData( array $conds ) {
720 $whereSQL = $this->makeList( $conds, LIST_AND );
721 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
722 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
723 // percision field is not supported in MySQL <= 5.5.
724 $res = $this->query(
725 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
726 );
727 $row = $res ? $res->fetchObject() : false;
728
729 return [ $row ? $row->ts : null, microtime( true ) ];
730 }
731
732 public function getApproximateLagStatus() {
733 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
734 // Disable caching since this is fast enough and we don't wan't
735 // to be *too* pessimistic by having both the cache TTL and the
736 // pt-heartbeat interval count as lag in getSessionLagStatus()
737 return parent::getApproximateLagStatus();
738 }
739
740 $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
741 $approxLag = $this->srvCache->get( $key );
742 if ( !$approxLag ) {
743 $approxLag = parent::getApproximateLagStatus();
744 $this->srvCache->set( $key, $approxLag, 1 );
745 }
746
747 return $approxLag;
748 }
749
750 function masterPosWait( DBMasterPos $pos, $timeout ) {
751 if ( !( $pos instanceof MySQLMasterPos ) ) {
752 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
753 }
754
755 if ( $this->getLBInfo( 'is static' ) === true ) {
756 return 0; // this is a copy of a read-only dataset with no master DB
757 } elseif ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
758 return 0; // already reached this point for sure
759 }
760
761 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
762 if ( $this->useGTIDs && $pos->gtids ) {
763 // Wait on the GTID set (MariaDB only)
764 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids ) );
765 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
766 } else {
767 // Wait on the binlog coordinates
768 $encFile = $this->addQuotes( $pos->file );
769 $encPos = intval( $pos->pos );
770 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
771 }
772
773 $row = $res ? $this->fetchRow( $res ) : false;
774 if ( !$row ) {
775 throw new DBExpectedError( $this, "Failed to query MASTER_POS_WAIT()" );
776 }
777
778 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
779 $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
780 if ( $status === null ) {
781 // T126436: jobs programmed to wait on master positions might be referencing binlogs
782 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
783 // to detect this and treat the slave as having reached the position; a proper master
784 // switchover already requires that the new master be caught up before the switch.
785 $slavePos = $this->getSlavePos();
786 if ( $slavePos && !$slavePos->channelsMatch( $pos ) ) {
787 $this->lastKnownSlavePos = $slavePos;
788 $status = 0;
789 }
790 } elseif ( $status >= 0 ) {
791 // Remember that this position was reached to save queries next time
792 $this->lastKnownSlavePos = $pos;
793 }
794
795 return $status;
796 }
797
798 /**
799 * Get the position of the master from SHOW SLAVE STATUS
800 *
801 * @return MySQLMasterPos|bool
802 */
803 function getSlavePos() {
804 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
805 $row = $this->fetchObject( $res );
806
807 if ( $row ) {
808 $pos = isset( $row->Exec_master_log_pos )
809 ? $row->Exec_master_log_pos
810 : $row->Exec_Master_Log_Pos;
811 // Also fetch the last-applied GTID set (MariaDB)
812 if ( $this->useGTIDs ) {
813 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__ );
814 $gtidRow = $this->fetchObject( $res );
815 $gtidSet = $gtidRow ? $gtidRow->Value : '';
816 } else {
817 $gtidSet = '';
818 }
819
820 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos, $gtidSet );
821 } else {
822 return false;
823 }
824 }
825
826 /**
827 * Get the position of the master from SHOW MASTER STATUS
828 *
829 * @return MySQLMasterPos|bool
830 */
831 function getMasterPos() {
832 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__ );
833 $row = $this->fetchObject( $res );
834
835 if ( $row ) {
836 // Also fetch the last-written GTID set (MariaDB)
837 if ( $this->useGTIDs ) {
838 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__ );
839 $gtidRow = $this->fetchObject( $res );
840 $gtidSet = $gtidRow ? $gtidRow->Value : '';
841 } else {
842 $gtidSet = '';
843 }
844
845 return new MySQLMasterPos( $row->File, $row->Position, $gtidSet );
846 } else {
847 return false;
848 }
849 }
850
851 public function serverIsReadOnly() {
852 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__ );
853 $row = $this->fetchObject( $res );
854
855 return $row ? ( strtolower( $row->Value ) === 'on' ) : false;
856 }
857
858 /**
859 * @param string $index
860 * @return string
861 */
862 function useIndexClause( $index ) {
863 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
864 }
865
866 /**
867 * @return string
868 */
869 function lowPriorityOption() {
870 return 'LOW_PRIORITY';
871 }
872
873 /**
874 * @return string
875 */
876 public function getSoftwareLink() {
877 // MariaDB includes its name in its version string; this is how MariaDB's version of
878 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
879 // in libmysql/libmysql.c).
880 $version = $this->getServerVersion();
881 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
882 return '[{{int:version-db-mariadb-url}} MariaDB]';
883 }
884
885 // Percona Server's version suffix is not very distinctive, and @@version_comment
886 // doesn't give the necessary info for source builds, so assume the server is MySQL.
887 // (Even Percona's version of mysql doesn't try to make the distinction.)
888 return '[{{int:version-db-mysql-url}} MySQL]';
889 }
890
891 /**
892 * @return string
893 */
894 public function getServerVersion() {
895 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
896 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
897 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
898 if ( $this->serverVersion === null ) {
899 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
900 }
901 return $this->serverVersion;
902 }
903
904 /**
905 * @param array $options
906 */
907 public function setSessionOptions( array $options ) {
908 if ( isset( $options['connTimeout'] ) ) {
909 $timeout = (int)$options['connTimeout'];
910 $this->query( "SET net_read_timeout=$timeout" );
911 $this->query( "SET net_write_timeout=$timeout" );
912 }
913 }
914
915 /**
916 * @param string $sql
917 * @param string $newLine
918 * @return bool
919 */
920 public function streamStatementEnd( &$sql, &$newLine ) {
921 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
922 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
923 $this->delimiter = $m[1];
924 $newLine = '';
925 }
926
927 return parent::streamStatementEnd( $sql, $newLine );
928 }
929
930 /**
931 * Check to see if a named lock is available. This is non-blocking.
932 *
933 * @param string $lockName Name of lock to poll
934 * @param string $method Name of method calling us
935 * @return bool
936 * @since 1.20
937 */
938 public function lockIsFree( $lockName, $method ) {
939 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
940 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
941 $row = $this->fetchObject( $result );
942
943 return ( $row->lockstatus == 1 );
944 }
945
946 /**
947 * @param string $lockName
948 * @param string $method
949 * @param int $timeout
950 * @return bool
951 */
952 public function lock( $lockName, $method, $timeout = 5 ) {
953 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
954 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
955 $row = $this->fetchObject( $result );
956
957 if ( $row->lockstatus == 1 ) {
958 parent::lock( $lockName, $method, $timeout ); // record
959 return true;
960 }
961
962 wfDebug( __METHOD__ . " failed to acquire lock\n" );
963
964 return false;
965 }
966
967 /**
968 * FROM MYSQL DOCS:
969 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
970 * @param string $lockName
971 * @param string $method
972 * @return bool
973 */
974 public function unlock( $lockName, $method ) {
975 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
976 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
977 $row = $this->fetchObject( $result );
978
979 if ( $row->lockstatus == 1 ) {
980 parent::unlock( $lockName, $method ); // record
981 return true;
982 }
983
984 wfDebug( __METHOD__ . " failed to release lock\n" );
985
986 return false;
987 }
988
989 private function makeLockName( $lockName ) {
990 // http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
991 // Newer version enforce a 64 char length limit.
992 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
993 }
994
995 public function namedLocksEnqueue() {
996 return true;
997 }
998
999 /**
1000 * @param array $read
1001 * @param array $write
1002 * @param string $method
1003 * @param bool $lowPriority
1004 * @return bool
1005 */
1006 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1007 $items = [];
1008
1009 foreach ( $write as $table ) {
1010 $tbl = $this->tableName( $table ) .
1011 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
1012 ' WRITE';
1013 $items[] = $tbl;
1014 }
1015 foreach ( $read as $table ) {
1016 $items[] = $this->tableName( $table ) . ' READ';
1017 }
1018 $sql = "LOCK TABLES " . implode( ',', $items );
1019 $this->query( $sql, $method );
1020
1021 return true;
1022 }
1023
1024 /**
1025 * @param string $method
1026 * @return bool
1027 */
1028 public function unlockTables( $method ) {
1029 $this->query( "UNLOCK TABLES", $method );
1030
1031 return true;
1032 }
1033
1034 /**
1035 * Get search engine class. All subclasses of this
1036 * need to implement this if they wish to use searching.
1037 *
1038 * @return string
1039 */
1040 public function getSearchEngine() {
1041 return 'SearchMySQL';
1042 }
1043
1044 /**
1045 * @param bool $value
1046 */
1047 public function setBigSelects( $value = true ) {
1048 if ( $value === 'default' ) {
1049 if ( $this->mDefaultBigSelects === null ) {
1050 # Function hasn't been called before so it must already be set to the default
1051 return;
1052 } else {
1053 $value = $this->mDefaultBigSelects;
1054 }
1055 } elseif ( $this->mDefaultBigSelects === null ) {
1056 $this->mDefaultBigSelects =
1057 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1058 }
1059 $encValue = $value ? '1' : '0';
1060 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
1061 }
1062
1063 /**
1064 * DELETE where the condition is a join. MySql uses multi-table deletes.
1065 * @param string $delTable
1066 * @param string $joinTable
1067 * @param string $delVar
1068 * @param string $joinVar
1069 * @param array|string $conds
1070 * @param bool|string $fname
1071 * @throws DBUnexpectedError
1072 * @return bool|ResultWrapper
1073 */
1074 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
1075 if ( !$conds ) {
1076 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1077 }
1078
1079 $delTable = $this->tableName( $delTable );
1080 $joinTable = $this->tableName( $joinTable );
1081 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1082
1083 if ( $conds != '*' ) {
1084 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1085 }
1086
1087 return $this->query( $sql, $fname );
1088 }
1089
1090 /**
1091 * @param string $table
1092 * @param array $rows
1093 * @param array $uniqueIndexes
1094 * @param array $set
1095 * @param string $fname
1096 * @return bool
1097 */
1098 public function upsert( $table, array $rows, array $uniqueIndexes,
1099 array $set, $fname = __METHOD__
1100 ) {
1101 if ( !count( $rows ) ) {
1102 return true; // nothing to do
1103 }
1104
1105 if ( !is_array( reset( $rows ) ) ) {
1106 $rows = [ $rows ];
1107 }
1108
1109 $table = $this->tableName( $table );
1110 $columns = array_keys( $rows[0] );
1111
1112 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1113 $rowTuples = [];
1114 foreach ( $rows as $row ) {
1115 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1116 }
1117 $sql .= implode( ',', $rowTuples );
1118 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
1119
1120 return (bool)$this->query( $sql, $fname );
1121 }
1122
1123 /**
1124 * Determines how long the server has been up
1125 *
1126 * @return int
1127 */
1128 function getServerUptime() {
1129 $vars = $this->getMysqlStatus( 'Uptime' );
1130
1131 return (int)$vars['Uptime'];
1132 }
1133
1134 /**
1135 * Determines if the last failure was due to a deadlock
1136 *
1137 * @return bool
1138 */
1139 function wasDeadlock() {
1140 return $this->lastErrno() == 1213;
1141 }
1142
1143 /**
1144 * Determines if the last failure was due to a lock timeout
1145 *
1146 * @return bool
1147 */
1148 function wasLockTimeout() {
1149 return $this->lastErrno() == 1205;
1150 }
1151
1152 function wasErrorReissuable() {
1153 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1154 }
1155
1156 /**
1157 * Determines if the last failure was due to the database being read-only.
1158 *
1159 * @return bool
1160 */
1161 function wasReadOnlyError() {
1162 return $this->lastErrno() == 1223 ||
1163 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1164 }
1165
1166 function wasConnectionError( $errno ) {
1167 return $errno == 2013 || $errno == 2006;
1168 }
1169
1170 /**
1171 * Get the underlying binding handle, mConn
1172 *
1173 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1174 * This catches broken callers than catch and ignore disconnection exceptions.
1175 * Unlike checking isOpen(), this is safe to call inside of open().
1176 *
1177 * @return resource|object
1178 * @throws DBUnexpectedError
1179 * @since 1.26
1180 */
1181 protected function getBindingHandle() {
1182 if ( !$this->mConn ) {
1183 throw new DBUnexpectedError(
1184 $this,
1185 'DB connection was already closed or the connection dropped.'
1186 );
1187 }
1188
1189 return $this->mConn;
1190 }
1191
1192 /**
1193 * @param string $oldName
1194 * @param string $newName
1195 * @param bool $temporary
1196 * @param string $fname
1197 * @return bool
1198 */
1199 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1200 $tmp = $temporary ? 'TEMPORARY ' : '';
1201 $newName = $this->addIdentifierQuotes( $newName );
1202 $oldName = $this->addIdentifierQuotes( $oldName );
1203 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1204
1205 return $this->query( $query, $fname );
1206 }
1207
1208 /**
1209 * List all tables on the database
1210 *
1211 * @param string $prefix Only show tables with this prefix, e.g. mw_
1212 * @param string $fname Calling function name
1213 * @return array
1214 */
1215 function listTables( $prefix = null, $fname = __METHOD__ ) {
1216 $result = $this->query( "SHOW TABLES", $fname );
1217
1218 $endArray = [];
1219
1220 foreach ( $result as $table ) {
1221 $vars = get_object_vars( $table );
1222 $table = array_pop( $vars );
1223
1224 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1225 $endArray[] = $table;
1226 }
1227 }
1228
1229 return $endArray;
1230 }
1231
1232 /**
1233 * @param string $tableName
1234 * @param string $fName
1235 * @return bool|ResultWrapper
1236 */
1237 public function dropTable( $tableName, $fName = __METHOD__ ) {
1238 if ( !$this->tableExists( $tableName, $fName ) ) {
1239 return false;
1240 }
1241
1242 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1243 }
1244
1245 /**
1246 * @return array
1247 */
1248 protected function getDefaultSchemaVars() {
1249 $vars = parent::getDefaultSchemaVars();
1250 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1251 $vars['wgDBTableOptions'] = str_replace(
1252 'CHARSET=mysql4',
1253 'CHARSET=binary',
1254 $vars['wgDBTableOptions']
1255 );
1256
1257 return $vars;
1258 }
1259
1260 /**
1261 * Get status information from SHOW STATUS in an associative array
1262 *
1263 * @param string $which
1264 * @return array
1265 */
1266 function getMysqlStatus( $which = "%" ) {
1267 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1268 $status = [];
1269
1270 foreach ( $res as $row ) {
1271 $status[$row->Variable_name] = $row->Value;
1272 }
1273
1274 return $status;
1275 }
1276
1277 /**
1278 * Lists VIEWs in the database
1279 *
1280 * @param string $prefix Only show VIEWs with this prefix, eg.
1281 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1282 * @param string $fname Name of calling function
1283 * @return array
1284 * @since 1.22
1285 */
1286 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1287
1288 if ( !isset( $this->allViews ) ) {
1289
1290 // The name of the column containing the name of the VIEW
1291 $propertyName = 'Tables_in_' . $this->mDBname;
1292
1293 // Query for the VIEWS
1294 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1295 $this->allViews = [];
1296 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1297 array_push( $this->allViews, $row[$propertyName] );
1298 }
1299 }
1300
1301 if ( is_null( $prefix ) || $prefix === '' ) {
1302 return $this->allViews;
1303 }
1304
1305 $filteredViews = [];
1306 foreach ( $this->allViews as $viewName ) {
1307 // Does the name of this VIEW start with the table-prefix?
1308 if ( strpos( $viewName, $prefix ) === 0 ) {
1309 array_push( $filteredViews, $viewName );
1310 }
1311 }
1312
1313 return $filteredViews;
1314 }
1315
1316 /**
1317 * Differentiates between a TABLE and a VIEW.
1318 *
1319 * @param string $name Name of the TABLE/VIEW to test
1320 * @param string $prefix
1321 * @return bool
1322 * @since 1.22
1323 */
1324 public function isView( $name, $prefix = null ) {
1325 return in_array( $name, $this->listViews( $prefix ) );
1326 }
1327 }
1328
1329 /**
1330 * Utility class.
1331 * @ingroup Database
1332 */
1333 class MySQLField implements Field {
1334 private $name, $tablename, $default, $max_length, $nullable,
1335 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1336 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1337
1338 function __construct( $info ) {
1339 $this->name = $info->name;
1340 $this->tablename = $info->table;
1341 $this->default = $info->def;
1342 $this->max_length = $info->max_length;
1343 $this->nullable = !$info->not_null;
1344 $this->is_pk = $info->primary_key;
1345 $this->is_unique = $info->unique_key;
1346 $this->is_multiple = $info->multiple_key;
1347 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1348 $this->type = $info->type;
1349 $this->binary = isset( $info->binary ) ? $info->binary : false;
1350 $this->is_numeric = isset( $info->numeric ) ? $info->numeric : false;
1351 $this->is_blob = isset( $info->blob ) ? $info->blob : false;
1352 $this->is_unsigned = isset( $info->unsigned ) ? $info->unsigned : false;
1353 $this->is_zerofill = isset( $info->zerofill ) ? $info->zerofill : false;
1354 }
1355
1356 /**
1357 * @return string
1358 */
1359 function name() {
1360 return $this->name;
1361 }
1362
1363 /**
1364 * @return string
1365 */
1366 function tableName() {
1367 return $this->tablename;
1368 }
1369
1370 /**
1371 * @return string
1372 */
1373 function type() {
1374 return $this->type;
1375 }
1376
1377 /**
1378 * @return bool
1379 */
1380 function isNullable() {
1381 return $this->nullable;
1382 }
1383
1384 function defaultValue() {
1385 return $this->default;
1386 }
1387
1388 /**
1389 * @return bool
1390 */
1391 function isKey() {
1392 return $this->is_key;
1393 }
1394
1395 /**
1396 * @return bool
1397 */
1398 function isMultipleKey() {
1399 return $this->is_multiple;
1400 }
1401
1402 /**
1403 * @return bool
1404 */
1405 function isBinary() {
1406 return $this->binary;
1407 }
1408
1409 /**
1410 * @return bool
1411 */
1412 function isNumeric() {
1413 return $this->is_numeric;
1414 }
1415
1416 /**
1417 * @return bool
1418 */
1419 function isBlob() {
1420 return $this->is_blob;
1421 }
1422
1423 /**
1424 * @return bool
1425 */
1426 function isUnsigned() {
1427 return $this->is_unsigned;
1428 }
1429
1430 /**
1431 * @return bool
1432 */
1433 function isZerofill() {
1434 return $this->is_zerofill;
1435 }
1436 }
1437
1438 /**
1439 * DBMasterPos class for MySQL/MariaDB
1440 *
1441 * Note that master positions and sync logic here make some assumptions:
1442 * - Binlog-based usage assumes single-source replication and non-hierarchical replication.
1443 * - GTID-based usage allows getting/syncing with multi-source replication. It is assumed
1444 * that GTID sets are complete (e.g. include all domains on the server).
1445 */
1446 class MySQLMasterPos implements DBMasterPos {
1447 /** @var string Binlog file */
1448 public $file;
1449 /** @var int Binglog file position */
1450 public $pos;
1451 /** @var string[] GTID list */
1452 public $gtids = [];
1453 /** @var float UNIX timestamp */
1454 public $asOfTime = 0.0;
1455
1456 /**
1457 * @param string $file Binlog file name
1458 * @param integer $pos Binlog position
1459 * @param string $gtid Comma separated GTID set [optional]
1460 */
1461 function __construct( $file, $pos, $gtid = '' ) {
1462 $this->file = $file;
1463 $this->pos = $pos;
1464 $this->gtids = array_map( 'trim', explode( ',', $gtid ) );
1465 $this->asOfTime = microtime( true );
1466 }
1467
1468 /**
1469 * @return string <binlog file>/<position>, e.g db1034-bin.000976/843431247
1470 */
1471 function __toString() {
1472 return "{$this->file}/{$this->pos}";
1473 }
1474
1475 function asOfTime() {
1476 return $this->asOfTime;
1477 }
1478
1479 function hasReached( DBMasterPos $pos ) {
1480 if ( !( $pos instanceof self ) ) {
1481 throw new InvalidArgumentException( "Position not an instance of " . __CLASS__ );
1482 }
1483
1484 // Prefer GTID comparisons, which work with multi-tier replication
1485 $thisPosByDomain = $this->getGtidCoordinates();
1486 $thatPosByDomain = $pos->getGtidCoordinates();
1487 if ( $thisPosByDomain && $thatPosByDomain ) {
1488 $reached = true;
1489 // Check that this has positions GTE all of those in $pos for all domains in $pos
1490 foreach ( $thatPosByDomain as $domain => $thatPos ) {
1491 $thisPos = isset( $thisPosByDomain[$domain] ) ? $thisPosByDomain[$domain] : -1;
1492 $reached = $reached && ( $thatPos <= $thisPos );
1493 }
1494
1495 return $reached;
1496 }
1497
1498 // Fallback to the binlog file comparisons
1499 $thisBinPos = $this->getBinlogCoordinates();
1500 $thatBinPos = $pos->getBinlogCoordinates();
1501 if ( $thisBinPos && $thatBinPos && $thisBinPos['binlog'] === $thatBinPos['binlog'] ) {
1502 return ( $thisBinPos['pos'] >= $thatBinPos['pos'] );
1503 }
1504
1505 // Comparing totally different binlogs does not make sense
1506 return false;
1507 }
1508
1509 function channelsMatch( DBMasterPos $pos ) {
1510 if ( !( $pos instanceof self ) ) {
1511 throw new InvalidArgumentException( "Position not an instance of " . __CLASS__ );
1512 }
1513
1514 // Prefer GTID comparisons, which work with multi-tier replication
1515 $thisPosDomains = array_keys( $this->getGtidCoordinates() );
1516 $thatPosDomains = array_keys( $pos->getGtidCoordinates() );
1517 if ( $thisPosDomains && $thatPosDomains ) {
1518 // Check that this has GTIDs for all domains in $pos
1519 return !array_diff( $thatPosDomains, $thisPosDomains );
1520 }
1521
1522 // Fallback to the binlog file comparisons
1523 $thisBinPos = $this->getBinlogCoordinates();
1524 $thatBinPos = $pos->getBinlogCoordinates();
1525
1526 return ( $thisBinPos && $thatBinPos && $thisBinPos['binlog'] === $thatBinPos['binlog'] );
1527 }
1528
1529 /**
1530 * @note: this returns false for multi-source replication GTID sets
1531 * @see https://mariadb.com/kb/en/mariadb/gtid
1532 * @see https://dev.mysql.com/doc/refman/5.6/en/replication-gtids-concepts.html
1533 * @return array Map of (domain => integer position) or false
1534 */
1535 protected function getGtidCoordinates() {
1536 $gtidInfos = [];
1537 foreach ( $this->gtids as $gtid ) {
1538 $m = [];
1539 // MariaDB style: <domain>-<server id>-<sequence number>
1540 if ( preg_match( '!^(\d+)-\d+-(\d+)$!', $gtid, $m ) ) {
1541 $gtidInfos[(int)$m[1]] = (int)$m[2];
1542 // MySQL style: <UUID domain>:<sequence number>
1543 } elseif ( preg_match( '!^(\w{8}-\w{4}-\w{4}-\w{4}-\w{12}):(\d+)$!', $gtid, $m ) ) {
1544 $gtidInfos[$m[1]] = (int)$m[2];
1545 } else {
1546 $gtidInfos = [];
1547 break; // unrecognized GTID
1548 }
1549
1550 }
1551
1552 return $gtidInfos;
1553 }
1554
1555 /**
1556 * @see http://dev.mysql.com/doc/refman/5.7/en/show-master-status.html
1557 * @see http://dev.mysql.com/doc/refman/5.7/en/show-slave-status.html
1558 * @return array|bool (binlog, (integer file number, integer position)) or false
1559 */
1560 protected function getBinlogCoordinates() {
1561 $m = [];
1562 if ( preg_match( '!^(.+)\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1563 return [ 'binlog' => $m[1], 'pos' => [ (int)$m[2], (int)$m[3] ] ];
1564 }
1565
1566 return false;
1567 }
1568 }