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