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