Merge "Add SPARQL client to core"
[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
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 ( strlen( $dbName ) ) {
163 Wikimedia\suppressWarnings();
164 $success = $this->selectDB( $dbName );
165 Wikimedia\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 Wikimedia\suppressWarnings();
261 $ok = $this->mysqlFreeResult( $res );
262 Wikimedia\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 Wikimedia\suppressWarnings();
286 $row = $this->mysqlFetchObject( $res );
287 Wikimedia\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 Wikimedia\suppressWarnings();
322 $row = $this->mysqlFetchArray( $res );
323 Wikimedia\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 Wikimedia\suppressWarnings();
358 $n = $this->mysqlNumRows( $res );
359 Wikimedia\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 Wikimedia\suppressWarnings();
471 $error = $this->mysqlError( $this->mConn );
472 if ( !$error ) {
473 $error = $this->mysqlError();
474 }
475 Wikimedia\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 = $row->Exec_Master_Log_Pos;
946 // Also fetch the last-applied GTID set (MariaDB)
947 if ( $this->useGTIDs ) {
948 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__ );
949 $gtidRow = $this->fetchObject( $res );
950 $gtidSet = $gtidRow ? $gtidRow->Value : '';
951 } else {
952 $gtidSet = '';
953 }
954
955 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos, $gtidSet );
956 } else {
957 return false;
958 }
959 }
960
961 /**
962 * Get the position of the master from SHOW MASTER STATUS
963 *
964 * @return MySQLMasterPos|bool
965 */
966 public function getMasterPos() {
967 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__ );
968 $row = $this->fetchObject( $res );
969
970 if ( $row ) {
971 // Also fetch the last-written GTID set (MariaDB)
972 if ( $this->useGTIDs ) {
973 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__ );
974 $gtidRow = $this->fetchObject( $res );
975 $gtidSet = $gtidRow ? $gtidRow->Value : '';
976 } else {
977 $gtidSet = '';
978 }
979
980 return new MySQLMasterPos( $row->File, $row->Position, $gtidSet );
981 } else {
982 return false;
983 }
984 }
985
986 public function serverIsReadOnly() {
987 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__ );
988 $row = $this->fetchObject( $res );
989
990 return $row ? ( strtolower( $row->Value ) === 'on' ) : false;
991 }
992
993 /**
994 * @param string $index
995 * @return string
996 */
997 function useIndexClause( $index ) {
998 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
999 }
1000
1001 /**
1002 * @param string $index
1003 * @return string
1004 */
1005 function ignoreIndexClause( $index ) {
1006 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1007 }
1008
1009 /**
1010 * @return string
1011 */
1012 function lowPriorityOption() {
1013 return 'LOW_PRIORITY';
1014 }
1015
1016 /**
1017 * @return string
1018 */
1019 public function getSoftwareLink() {
1020 // MariaDB includes its name in its version string; this is how MariaDB's version of
1021 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1022 // in libmysql/libmysql.c).
1023 $version = $this->getServerVersion();
1024 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
1025 return '[{{int:version-db-mariadb-url}} MariaDB]';
1026 }
1027
1028 // Percona Server's version suffix is not very distinctive, and @@version_comment
1029 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1030 // (Even Percona's version of mysql doesn't try to make the distinction.)
1031 return '[{{int:version-db-mysql-url}} MySQL]';
1032 }
1033
1034 /**
1035 * @return string
1036 */
1037 public function getServerVersion() {
1038 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1039 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1040 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1041 if ( $this->serverVersion === null ) {
1042 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
1043 }
1044 return $this->serverVersion;
1045 }
1046
1047 /**
1048 * @param array $options
1049 */
1050 public function setSessionOptions( array $options ) {
1051 if ( isset( $options['connTimeout'] ) ) {
1052 $timeout = (int)$options['connTimeout'];
1053 $this->query( "SET net_read_timeout=$timeout" );
1054 $this->query( "SET net_write_timeout=$timeout" );
1055 }
1056 }
1057
1058 /**
1059 * @param string &$sql
1060 * @param string &$newLine
1061 * @return bool
1062 */
1063 public function streamStatementEnd( &$sql, &$newLine ) {
1064 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1065 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1066 $this->delimiter = $m[1];
1067 $newLine = '';
1068 }
1069
1070 return parent::streamStatementEnd( $sql, $newLine );
1071 }
1072
1073 /**
1074 * Check to see if a named lock is available. This is non-blocking.
1075 *
1076 * @param string $lockName Name of lock to poll
1077 * @param string $method Name of method calling us
1078 * @return bool
1079 * @since 1.20
1080 */
1081 public function lockIsFree( $lockName, $method ) {
1082 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1083 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1084 $row = $this->fetchObject( $result );
1085
1086 return ( $row->lockstatus == 1 );
1087 }
1088
1089 /**
1090 * @param string $lockName
1091 * @param string $method
1092 * @param int $timeout
1093 * @return bool
1094 */
1095 public function lock( $lockName, $method, $timeout = 5 ) {
1096 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1097 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1098 $row = $this->fetchObject( $result );
1099
1100 if ( $row->lockstatus == 1 ) {
1101 parent::lock( $lockName, $method, $timeout ); // record
1102 return true;
1103 }
1104
1105 $this->queryLogger->info( __METHOD__ . " failed to acquire lock '{lockname}'",
1106 [ 'lockname' => $lockName ] );
1107
1108 return false;
1109 }
1110
1111 /**
1112 * FROM MYSQL DOCS:
1113 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1114 * @param string $lockName
1115 * @param string $method
1116 * @return bool
1117 */
1118 public function unlock( $lockName, $method ) {
1119 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1120 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1121 $row = $this->fetchObject( $result );
1122
1123 if ( $row->lockstatus == 1 ) {
1124 parent::unlock( $lockName, $method ); // record
1125 return true;
1126 }
1127
1128 $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
1129
1130 return false;
1131 }
1132
1133 private function makeLockName( $lockName ) {
1134 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1135 // Newer version enforce a 64 char length limit.
1136 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1137 }
1138
1139 public function namedLocksEnqueue() {
1140 return true;
1141 }
1142
1143 public function tableLocksHaveTransactionScope() {
1144 return false; // tied to TCP connection
1145 }
1146
1147 protected function doLockTables( array $read, array $write, $method ) {
1148 $items = [];
1149 foreach ( $write as $table ) {
1150 $items[] = $this->tableName( $table ) . ' WRITE';
1151 }
1152 foreach ( $read as $table ) {
1153 $items[] = $this->tableName( $table ) . ' READ';
1154 }
1155
1156 $sql = "LOCK TABLES " . implode( ',', $items );
1157 $this->query( $sql, $method );
1158
1159 return true;
1160 }
1161
1162 protected function doUnlockTables( $method ) {
1163 $this->query( "UNLOCK TABLES", $method );
1164
1165 return true;
1166 }
1167
1168 /**
1169 * @param bool $value
1170 */
1171 public function setBigSelects( $value = true ) {
1172 if ( $value === 'default' ) {
1173 if ( $this->mDefaultBigSelects === null ) {
1174 # Function hasn't been called before so it must already be set to the default
1175 return;
1176 } else {
1177 $value = $this->mDefaultBigSelects;
1178 }
1179 } elseif ( $this->mDefaultBigSelects === null ) {
1180 $this->mDefaultBigSelects =
1181 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1182 }
1183 $encValue = $value ? '1' : '0';
1184 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
1185 }
1186
1187 /**
1188 * DELETE where the condition is a join. MySql uses multi-table deletes.
1189 * @param string $delTable
1190 * @param string $joinTable
1191 * @param string $delVar
1192 * @param string $joinVar
1193 * @param array|string $conds
1194 * @param bool|string $fname
1195 * @throws DBUnexpectedError
1196 * @return bool|ResultWrapper
1197 */
1198 public function deleteJoin(
1199 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1200 ) {
1201 if ( !$conds ) {
1202 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1203 }
1204
1205 $delTable = $this->tableName( $delTable );
1206 $joinTable = $this->tableName( $joinTable );
1207 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1208
1209 if ( $conds != '*' ) {
1210 $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1211 }
1212
1213 return $this->query( $sql, $fname );
1214 }
1215
1216 /**
1217 * @param string $table
1218 * @param array $rows
1219 * @param array $uniqueIndexes
1220 * @param array $set
1221 * @param string $fname
1222 * @return bool
1223 */
1224 public function upsert( $table, array $rows, array $uniqueIndexes,
1225 array $set, $fname = __METHOD__
1226 ) {
1227 if ( !count( $rows ) ) {
1228 return true; // nothing to do
1229 }
1230
1231 if ( !is_array( reset( $rows ) ) ) {
1232 $rows = [ $rows ];
1233 }
1234
1235 $table = $this->tableName( $table );
1236 $columns = array_keys( $rows[0] );
1237
1238 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1239 $rowTuples = [];
1240 foreach ( $rows as $row ) {
1241 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1242 }
1243 $sql .= implode( ',', $rowTuples );
1244 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
1245
1246 return (bool)$this->query( $sql, $fname );
1247 }
1248
1249 /**
1250 * Determines how long the server has been up
1251 *
1252 * @return int
1253 */
1254 public function getServerUptime() {
1255 $vars = $this->getMysqlStatus( 'Uptime' );
1256
1257 return (int)$vars['Uptime'];
1258 }
1259
1260 /**
1261 * Determines if the last failure was due to a deadlock
1262 *
1263 * @return bool
1264 */
1265 public function wasDeadlock() {
1266 return $this->lastErrno() == 1213;
1267 }
1268
1269 /**
1270 * Determines if the last failure was due to a lock timeout
1271 *
1272 * @return bool
1273 */
1274 public function wasLockTimeout() {
1275 return $this->lastErrno() == 1205;
1276 }
1277
1278 public function wasErrorReissuable() {
1279 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1280 }
1281
1282 /**
1283 * Determines if the last failure was due to the database being read-only.
1284 *
1285 * @return bool
1286 */
1287 public function wasReadOnlyError() {
1288 return $this->lastErrno() == 1223 ||
1289 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1290 }
1291
1292 public function wasConnectionError( $errno ) {
1293 return $errno == 2013 || $errno == 2006;
1294 }
1295
1296 /**
1297 * @param string $oldName
1298 * @param string $newName
1299 * @param bool $temporary
1300 * @param string $fname
1301 * @return bool
1302 */
1303 public function duplicateTableStructure(
1304 $oldName, $newName, $temporary = false, $fname = __METHOD__
1305 ) {
1306 $tmp = $temporary ? 'TEMPORARY ' : '';
1307 $newName = $this->addIdentifierQuotes( $newName );
1308 $oldName = $this->addIdentifierQuotes( $oldName );
1309 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1310
1311 return $this->query( $query, $fname );
1312 }
1313
1314 /**
1315 * List all tables on the database
1316 *
1317 * @param string $prefix Only show tables with this prefix, e.g. mw_
1318 * @param string $fname Calling function name
1319 * @return array
1320 */
1321 public function listTables( $prefix = null, $fname = __METHOD__ ) {
1322 $result = $this->query( "SHOW TABLES", $fname );
1323
1324 $endArray = [];
1325
1326 foreach ( $result as $table ) {
1327 $vars = get_object_vars( $table );
1328 $table = array_pop( $vars );
1329
1330 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1331 $endArray[] = $table;
1332 }
1333 }
1334
1335 return $endArray;
1336 }
1337
1338 /**
1339 * @param string $tableName
1340 * @param string $fName
1341 * @return bool|ResultWrapper
1342 */
1343 public function dropTable( $tableName, $fName = __METHOD__ ) {
1344 if ( !$this->tableExists( $tableName, $fName ) ) {
1345 return false;
1346 }
1347
1348 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1349 }
1350
1351 /**
1352 * Get status information from SHOW STATUS in an associative array
1353 *
1354 * @param string $which
1355 * @return array
1356 */
1357 private function getMysqlStatus( $which = "%" ) {
1358 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1359 $status = [];
1360
1361 foreach ( $res as $row ) {
1362 $status[$row->Variable_name] = $row->Value;
1363 }
1364
1365 return $status;
1366 }
1367
1368 /**
1369 * Lists VIEWs in the database
1370 *
1371 * @param string $prefix Only show VIEWs with this prefix, eg.
1372 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1373 * @param string $fname Name of calling function
1374 * @return array
1375 * @since 1.22
1376 */
1377 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1378 // The name of the column containing the name of the VIEW
1379 $propertyName = 'Tables_in_' . $this->mDBname;
1380
1381 // Query for the VIEWS
1382 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1383 $allViews = [];
1384 foreach ( $res as $row ) {
1385 array_push( $allViews, $row->$propertyName );
1386 }
1387
1388 if ( is_null( $prefix ) || $prefix === '' ) {
1389 return $allViews;
1390 }
1391
1392 $filteredViews = [];
1393 foreach ( $allViews as $viewName ) {
1394 // Does the name of this VIEW start with the table-prefix?
1395 if ( strpos( $viewName, $prefix ) === 0 ) {
1396 array_push( $filteredViews, $viewName );
1397 }
1398 }
1399
1400 return $filteredViews;
1401 }
1402
1403 /**
1404 * Differentiates between a TABLE and a VIEW.
1405 *
1406 * @param string $name Name of the TABLE/VIEW to test
1407 * @param string $prefix
1408 * @return bool
1409 * @since 1.22
1410 */
1411 public function isView( $name, $prefix = null ) {
1412 return in_array( $name, $this->listViews( $prefix ) );
1413 }
1414
1415 /**
1416 * Allows for index remapping in queries where this is not consistent across DBMS
1417 *
1418 * @param string $index
1419 * @return string
1420 */
1421 protected function indexName( $index ) {
1422 /**
1423 * When SQLite indexes were introduced in r45764, it was noted that
1424 * SQLite requires index names to be unique within the whole database,
1425 * not just within a schema. As discussed in CR r45819, to avoid the
1426 * need for a schema change on existing installations, the indexes
1427 * were implicitly mapped from the new names to the old names.
1428 *
1429 * This mapping can be removed if DB patches are introduced to alter
1430 * the relevant tables in existing installations. Note that because
1431 * this index mapping applies to table creation, even new installations
1432 * of MySQL have the old names (except for installations created during
1433 * a period where this mapping was inappropriately removed, see
1434 * T154872).
1435 */
1436 $renamed = [
1437 'ar_usertext_timestamp' => 'usertext_timestamp',
1438 'un_user_id' => 'user_id',
1439 'un_user_ip' => 'user_ip',
1440 ];
1441
1442 if ( isset( $renamed[$index] ) ) {
1443 return $renamed[$index];
1444 } else {
1445 return $index;
1446 }
1447 }
1448 }
1449
1450 class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );