Merge "Add support for PHP7 random_bytes in favor of mcrypt_create_iv"
[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 $encLike = $this->buildLike( $table );
532
533 return $this->query( "SHOW TABLES $encLike", $fname )->numRows() > 0;
534 }
535
536 /**
537 * @param string $table
538 * @param string $field
539 * @return bool|MySQLField
540 */
541 public function fieldInfo( $table, $field ) {
542 $table = $this->tableName( $table );
543 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
544 if ( !$res ) {
545 return false;
546 }
547 $n = $this->mysqlNumFields( $res->result );
548 for ( $i = 0; $i < $n; $i++ ) {
549 $meta = $this->mysqlFetchField( $res->result, $i );
550 if ( $field == $meta->name ) {
551 return new MySQLField( $meta );
552 }
553 }
554
555 return false;
556 }
557
558 /**
559 * Get column information from a result
560 *
561 * @param resource $res Raw result
562 * @param int $n
563 * @return stdClass
564 */
565 abstract protected function mysqlFetchField( $res, $n );
566
567 /**
568 * Get information about an index into an object
569 * Returns false if the index does not exist
570 *
571 * @param string $table
572 * @param string $index
573 * @param string $fname
574 * @return bool|array|null False or null on failure
575 */
576 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
577 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
578 # SHOW INDEX should work for 3.x and up:
579 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
580 $table = $this->tableName( $table );
581 $index = $this->indexName( $index );
582
583 $sql = 'SHOW INDEX FROM ' . $table;
584 $res = $this->query( $sql, $fname );
585
586 if ( !$res ) {
587 return null;
588 }
589
590 $result = [];
591
592 foreach ( $res as $row ) {
593 if ( $row->Key_name == $index ) {
594 $result[] = $row;
595 }
596 }
597
598 return empty( $result ) ? false : $result;
599 }
600
601 /**
602 * @param string $s
603 * @return string
604 */
605 public function strencode( $s ) {
606 return $this->mysqlRealEscapeString( $s );
607 }
608
609 /**
610 * @param string $s
611 * @return mixed
612 */
613 abstract protected function mysqlRealEscapeString( $s );
614
615 public function addQuotes( $s ) {
616 if ( is_bool( $s ) ) {
617 // Parent would transform to int, which does not play nice with MySQL type juggling.
618 // When searching for an int in a string column, the strings are cast to int, which
619 // means false would match any string not starting with a number.
620 $s = (string)(int)$s;
621 }
622 return parent::addQuotes( $s );
623 }
624
625 /**
626 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
627 *
628 * @param string $s
629 * @return string
630 */
631 public function addIdentifierQuotes( $s ) {
632 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
633 // Remove NUL bytes and escape backticks by doubling
634 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
635 }
636
637 /**
638 * @param string $name
639 * @return bool
640 */
641 public function isQuotedIdentifier( $name ) {
642 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
643 }
644
645 public function getLag() {
646 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
647 return $this->getLagFromPtHeartbeat();
648 } else {
649 return $this->getLagFromSlaveStatus();
650 }
651 }
652
653 /**
654 * @return string
655 */
656 protected function getLagDetectionMethod() {
657 return $this->lagDetectionMethod;
658 }
659
660 /**
661 * @return bool|int
662 */
663 protected function getLagFromSlaveStatus() {
664 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
665 $row = $res ? $res->fetchObject() : false;
666 if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
667 return intval( $row->Seconds_Behind_Master );
668 }
669
670 return false;
671 }
672
673 /**
674 * @return bool|float
675 */
676 protected function getLagFromPtHeartbeat() {
677 $options = $this->lagDetectionOptions;
678
679 if ( isset( $options['conds'] ) ) {
680 // Best method for multi-DC setups: use logical channel names
681 $data = $this->getHeartbeatData( $options['conds'] );
682 } else {
683 // Standard method: use master server ID (works with stock pt-heartbeat)
684 $masterInfo = $this->getMasterServerInfo();
685 if ( !$masterInfo ) {
686 $this->queryLogger->error(
687 "Unable to query master of {db_server} for server ID",
688 $this->getLogContext( [
689 'method' => __METHOD__
690 ] )
691 );
692
693 return false; // could not get master server ID
694 }
695
696 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
697 $data = $this->getHeartbeatData( $conds );
698 }
699
700 list( $time, $nowUnix ) = $data;
701 if ( $time !== null ) {
702 // @time is in ISO format like "2015-09-25T16:48:10.000510"
703 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
704 $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
705
706 return max( $nowUnix - $timeUnix, 0.0 );
707 }
708
709 $this->queryLogger->error(
710 "Unable to find pt-heartbeat row for {db_server}",
711 $this->getLogContext( [
712 'method' => __METHOD__
713 ] )
714 );
715
716 return false;
717 }
718
719 protected function getMasterServerInfo() {
720 $cache = $this->srvCache;
721 $key = $cache->makeGlobalKey(
722 'mysql',
723 'master-info',
724 // Using one key for all cluster replica DBs is preferable
725 $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
726 );
727
728 return $cache->getWithSetCallback(
729 $key,
730 $cache::TTL_INDEFINITE,
731 function () use ( $cache, $key ) {
732 // Get and leave a lock key in place for a short period
733 if ( !$cache->lock( $key, 0, 10 ) ) {
734 return false; // avoid master connection spike slams
735 }
736
737 $conn = $this->getLazyMasterHandle();
738 if ( !$conn ) {
739 return false; // something is misconfigured
740 }
741
742 // Connect to and query the master; catch errors to avoid outages
743 try {
744 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__ );
745 $row = $res ? $res->fetchObject() : false;
746 $id = $row ? (int)$row->id : 0;
747 } catch ( DBError $e ) {
748 $id = 0;
749 }
750
751 // Cache the ID if it was retrieved
752 return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
753 }
754 );
755 }
756
757 /**
758 * @param array $conds WHERE clause conditions to find a row
759 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
760 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
761 */
762 protected function getHeartbeatData( array $conds ) {
763 // Do not bother starting implicit transactions here
764 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
765 try {
766 $whereSQL = $this->makeList( $conds, self::LIST_AND );
767 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
768 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
769 // percision field is not supported in MySQL <= 5.5.
770 $res = $this->query(
771 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
772 );
773 $row = $res ? $res->fetchObject() : false;
774 } finally {
775 $this->restoreFlags();
776 }
777
778 return [ $row ? $row->ts : null, microtime( true ) ];
779 }
780
781 protected function getApproximateLagStatus() {
782 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
783 // Disable caching since this is fast enough and we don't wan't
784 // to be *too* pessimistic by having both the cache TTL and the
785 // pt-heartbeat interval count as lag in getSessionLagStatus()
786 return parent::getApproximateLagStatus();
787 }
788
789 $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
790 $approxLag = $this->srvCache->get( $key );
791 if ( !$approxLag ) {
792 $approxLag = parent::getApproximateLagStatus();
793 $this->srvCache->set( $key, $approxLag, 1 );
794 }
795
796 return $approxLag;
797 }
798
799 public function masterPosWait( DBMasterPos $pos, $timeout ) {
800 if ( !( $pos instanceof MySQLMasterPos ) ) {
801 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
802 }
803
804 if ( $this->getLBInfo( 'is static' ) === true ) {
805 return 0; // this is a copy of a read-only dataset with no master DB
806 } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
807 return 0; // already reached this point for sure
808 }
809
810 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
811 if ( $this->useGTIDs && $pos->gtids ) {
812 // Wait on the GTID set (MariaDB only)
813 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids ) );
814 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
815 } else {
816 // Wait on the binlog coordinates
817 $encFile = $this->addQuotes( $pos->file );
818 $encPos = intval( $pos->pos );
819 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
820 }
821
822 $row = $res ? $this->fetchRow( $res ) : false;
823 if ( !$row ) {
824 throw new DBExpectedError( $this,
825 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
826 }
827
828 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
829 $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
830 if ( $status === null ) {
831 // T126436: jobs programmed to wait on master positions might be referencing binlogs
832 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
833 // to detect this and treat the replica DB as having reached the position; a proper master
834 // switchover already requires that the new master be caught up before the switch.
835 $replicationPos = $this->getReplicaPos();
836 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
837 $this->lastKnownReplicaPos = $replicationPos;
838 $status = 0;
839 }
840 } elseif ( $status >= 0 ) {
841 // Remember that this position was reached to save queries next time
842 $this->lastKnownReplicaPos = $pos;
843 }
844
845 return $status;
846 }
847
848 /**
849 * Get the position of the master from SHOW SLAVE STATUS
850 *
851 * @return MySQLMasterPos|bool
852 */
853 public function getReplicaPos() {
854 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
855 $row = $this->fetchObject( $res );
856
857 if ( $row ) {
858 $pos = isset( $row->Exec_master_log_pos )
859 ? $row->Exec_master_log_pos
860 : $row->Exec_Master_Log_Pos;
861 // Also fetch the last-applied GTID set (MariaDB)
862 if ( $this->useGTIDs ) {
863 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__ );
864 $gtidRow = $this->fetchObject( $res );
865 $gtidSet = $gtidRow ? $gtidRow->Value : '';
866 } else {
867 $gtidSet = '';
868 }
869
870 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos, $gtidSet );
871 } else {
872 return false;
873 }
874 }
875
876 /**
877 * Get the position of the master from SHOW MASTER STATUS
878 *
879 * @return MySQLMasterPos|bool
880 */
881 public function getMasterPos() {
882 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__ );
883 $row = $this->fetchObject( $res );
884
885 if ( $row ) {
886 // Also fetch the last-written GTID set (MariaDB)
887 if ( $this->useGTIDs ) {
888 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__ );
889 $gtidRow = $this->fetchObject( $res );
890 $gtidSet = $gtidRow ? $gtidRow->Value : '';
891 } else {
892 $gtidSet = '';
893 }
894
895 return new MySQLMasterPos( $row->File, $row->Position, $gtidSet );
896 } else {
897 return false;
898 }
899 }
900
901 public function serverIsReadOnly() {
902 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__ );
903 $row = $this->fetchObject( $res );
904
905 return $row ? ( strtolower( $row->Value ) === 'on' ) : false;
906 }
907
908 /**
909 * @param string $index
910 * @return string
911 */
912 function useIndexClause( $index ) {
913 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
914 }
915
916 /**
917 * @param string $index
918 * @return string
919 */
920 function ignoreIndexClause( $index ) {
921 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
922 }
923
924 /**
925 * @return string
926 */
927 function lowPriorityOption() {
928 return 'LOW_PRIORITY';
929 }
930
931 /**
932 * @return string
933 */
934 public function getSoftwareLink() {
935 // MariaDB includes its name in its version string; this is how MariaDB's version of
936 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
937 // in libmysql/libmysql.c).
938 $version = $this->getServerVersion();
939 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
940 return '[{{int:version-db-mariadb-url}} MariaDB]';
941 }
942
943 // Percona Server's version suffix is not very distinctive, and @@version_comment
944 // doesn't give the necessary info for source builds, so assume the server is MySQL.
945 // (Even Percona's version of mysql doesn't try to make the distinction.)
946 return '[{{int:version-db-mysql-url}} MySQL]';
947 }
948
949 /**
950 * @return string
951 */
952 public function getServerVersion() {
953 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
954 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
955 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
956 if ( $this->serverVersion === null ) {
957 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
958 }
959 return $this->serverVersion;
960 }
961
962 /**
963 * @param array $options
964 */
965 public function setSessionOptions( array $options ) {
966 if ( isset( $options['connTimeout'] ) ) {
967 $timeout = (int)$options['connTimeout'];
968 $this->query( "SET net_read_timeout=$timeout" );
969 $this->query( "SET net_write_timeout=$timeout" );
970 }
971 }
972
973 /**
974 * @param string $sql
975 * @param string $newLine
976 * @return bool
977 */
978 public function streamStatementEnd( &$sql, &$newLine ) {
979 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
980 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
981 $this->delimiter = $m[1];
982 $newLine = '';
983 }
984
985 return parent::streamStatementEnd( $sql, $newLine );
986 }
987
988 /**
989 * Check to see if a named lock is available. This is non-blocking.
990 *
991 * @param string $lockName Name of lock to poll
992 * @param string $method Name of method calling us
993 * @return bool
994 * @since 1.20
995 */
996 public function lockIsFree( $lockName, $method ) {
997 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
998 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
999 $row = $this->fetchObject( $result );
1000
1001 return ( $row->lockstatus == 1 );
1002 }
1003
1004 /**
1005 * @param string $lockName
1006 * @param string $method
1007 * @param int $timeout
1008 * @return bool
1009 */
1010 public function lock( $lockName, $method, $timeout = 5 ) {
1011 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1012 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1013 $row = $this->fetchObject( $result );
1014
1015 if ( $row->lockstatus == 1 ) {
1016 parent::lock( $lockName, $method, $timeout ); // record
1017 return true;
1018 }
1019
1020 $this->queryLogger->warning( __METHOD__ . " failed to acquire lock '$lockName'\n" );
1021
1022 return false;
1023 }
1024
1025 /**
1026 * FROM MYSQL DOCS:
1027 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1028 * @param string $lockName
1029 * @param string $method
1030 * @return bool
1031 */
1032 public function unlock( $lockName, $method ) {
1033 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1034 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1035 $row = $this->fetchObject( $result );
1036
1037 if ( $row->lockstatus == 1 ) {
1038 parent::unlock( $lockName, $method ); // record
1039 return true;
1040 }
1041
1042 $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
1043
1044 return false;
1045 }
1046
1047 private function makeLockName( $lockName ) {
1048 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1049 // Newer version enforce a 64 char length limit.
1050 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1051 }
1052
1053 public function namedLocksEnqueue() {
1054 return true;
1055 }
1056
1057 /**
1058 * @param array $read
1059 * @param array $write
1060 * @param string $method
1061 * @param bool $lowPriority
1062 * @return bool
1063 */
1064 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1065 $items = [];
1066
1067 foreach ( $write as $table ) {
1068 $tbl = $this->tableName( $table ) .
1069 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
1070 ' WRITE';
1071 $items[] = $tbl;
1072 }
1073 foreach ( $read as $table ) {
1074 $items[] = $this->tableName( $table ) . ' READ';
1075 }
1076 $sql = "LOCK TABLES " . implode( ',', $items );
1077 $this->query( $sql, $method );
1078
1079 return true;
1080 }
1081
1082 /**
1083 * @param string $method
1084 * @return bool
1085 */
1086 public function unlockTables( $method ) {
1087 $this->query( "UNLOCK TABLES", $method );
1088
1089 return true;
1090 }
1091
1092 /**
1093 * @param bool $value
1094 */
1095 public function setBigSelects( $value = true ) {
1096 if ( $value === 'default' ) {
1097 if ( $this->mDefaultBigSelects === null ) {
1098 # Function hasn't been called before so it must already be set to the default
1099 return;
1100 } else {
1101 $value = $this->mDefaultBigSelects;
1102 }
1103 } elseif ( $this->mDefaultBigSelects === null ) {
1104 $this->mDefaultBigSelects =
1105 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1106 }
1107 $encValue = $value ? '1' : '0';
1108 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
1109 }
1110
1111 /**
1112 * DELETE where the condition is a join. MySql uses multi-table deletes.
1113 * @param string $delTable
1114 * @param string $joinTable
1115 * @param string $delVar
1116 * @param string $joinVar
1117 * @param array|string $conds
1118 * @param bool|string $fname
1119 * @throws DBUnexpectedError
1120 * @return bool|ResultWrapper
1121 */
1122 public function deleteJoin(
1123 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1124 ) {
1125 if ( !$conds ) {
1126 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1127 }
1128
1129 $delTable = $this->tableName( $delTable );
1130 $joinTable = $this->tableName( $joinTable );
1131 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1132
1133 if ( $conds != '*' ) {
1134 $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1135 }
1136
1137 return $this->query( $sql, $fname );
1138 }
1139
1140 /**
1141 * @param string $table
1142 * @param array $rows
1143 * @param array $uniqueIndexes
1144 * @param array $set
1145 * @param string $fname
1146 * @return bool
1147 */
1148 public function upsert( $table, array $rows, array $uniqueIndexes,
1149 array $set, $fname = __METHOD__
1150 ) {
1151 if ( !count( $rows ) ) {
1152 return true; // nothing to do
1153 }
1154
1155 if ( !is_array( reset( $rows ) ) ) {
1156 $rows = [ $rows ];
1157 }
1158
1159 $table = $this->tableName( $table );
1160 $columns = array_keys( $rows[0] );
1161
1162 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1163 $rowTuples = [];
1164 foreach ( $rows as $row ) {
1165 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1166 }
1167 $sql .= implode( ',', $rowTuples );
1168 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
1169
1170 return (bool)$this->query( $sql, $fname );
1171 }
1172
1173 /**
1174 * Determines how long the server has been up
1175 *
1176 * @return int
1177 */
1178 public function getServerUptime() {
1179 $vars = $this->getMysqlStatus( 'Uptime' );
1180
1181 return (int)$vars['Uptime'];
1182 }
1183
1184 /**
1185 * Determines if the last failure was due to a deadlock
1186 *
1187 * @return bool
1188 */
1189 public function wasDeadlock() {
1190 return $this->lastErrno() == 1213;
1191 }
1192
1193 /**
1194 * Determines if the last failure was due to a lock timeout
1195 *
1196 * @return bool
1197 */
1198 public function wasLockTimeout() {
1199 return $this->lastErrno() == 1205;
1200 }
1201
1202 public function wasErrorReissuable() {
1203 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1204 }
1205
1206 /**
1207 * Determines if the last failure was due to the database being read-only.
1208 *
1209 * @return bool
1210 */
1211 public function wasReadOnlyError() {
1212 return $this->lastErrno() == 1223 ||
1213 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1214 }
1215
1216 public function wasConnectionError( $errno ) {
1217 return $errno == 2013 || $errno == 2006;
1218 }
1219
1220 /**
1221 * @param string $oldName
1222 * @param string $newName
1223 * @param bool $temporary
1224 * @param string $fname
1225 * @return bool
1226 */
1227 public function duplicateTableStructure(
1228 $oldName, $newName, $temporary = false, $fname = __METHOD__
1229 ) {
1230 $tmp = $temporary ? 'TEMPORARY ' : '';
1231 $newName = $this->addIdentifierQuotes( $newName );
1232 $oldName = $this->addIdentifierQuotes( $oldName );
1233 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1234
1235 return $this->query( $query, $fname );
1236 }
1237
1238 /**
1239 * List all tables on the database
1240 *
1241 * @param string $prefix Only show tables with this prefix, e.g. mw_
1242 * @param string $fname Calling function name
1243 * @return array
1244 */
1245 public function listTables( $prefix = null, $fname = __METHOD__ ) {
1246 $result = $this->query( "SHOW TABLES", $fname );
1247
1248 $endArray = [];
1249
1250 foreach ( $result as $table ) {
1251 $vars = get_object_vars( $table );
1252 $table = array_pop( $vars );
1253
1254 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1255 $endArray[] = $table;
1256 }
1257 }
1258
1259 return $endArray;
1260 }
1261
1262 /**
1263 * @param string $tableName
1264 * @param string $fName
1265 * @return bool|ResultWrapper
1266 */
1267 public function dropTable( $tableName, $fName = __METHOD__ ) {
1268 if ( !$this->tableExists( $tableName, $fName ) ) {
1269 return false;
1270 }
1271
1272 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1273 }
1274
1275 /**
1276 * Get status information from SHOW STATUS in an associative array
1277 *
1278 * @param string $which
1279 * @return array
1280 */
1281 private function getMysqlStatus( $which = "%" ) {
1282 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1283 $status = [];
1284
1285 foreach ( $res as $row ) {
1286 $status[$row->Variable_name] = $row->Value;
1287 }
1288
1289 return $status;
1290 }
1291
1292 /**
1293 * Lists VIEWs in the database
1294 *
1295 * @param string $prefix Only show VIEWs with this prefix, eg.
1296 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1297 * @param string $fname Name of calling function
1298 * @return array
1299 * @since 1.22
1300 */
1301 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1302 // The name of the column containing the name of the VIEW
1303 $propertyName = 'Tables_in_' . $this->mDBname;
1304
1305 // Query for the VIEWS
1306 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1307 $allViews = [];
1308 foreach ( $res as $row ) {
1309 array_push( $allViews, $row->$propertyName );
1310 }
1311
1312 if ( is_null( $prefix ) || $prefix === '' ) {
1313 return $allViews;
1314 }
1315
1316 $filteredViews = [];
1317 foreach ( $allViews as $viewName ) {
1318 // Does the name of this VIEW start with the table-prefix?
1319 if ( strpos( $viewName, $prefix ) === 0 ) {
1320 array_push( $filteredViews, $viewName );
1321 }
1322 }
1323
1324 return $filteredViews;
1325 }
1326
1327 /**
1328 * Differentiates between a TABLE and a VIEW.
1329 *
1330 * @param string $name Name of the TABLE/VIEW to test
1331 * @param string $prefix
1332 * @return bool
1333 * @since 1.22
1334 */
1335 public function isView( $name, $prefix = null ) {
1336 return in_array( $name, $this->listViews( $prefix ) );
1337 }
1338 }