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