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