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