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