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