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