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