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