Merge "rdbms: migrate DatabaseMysqlBase::getServerVersion() to using the local server...
[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 return 0; // this is a copy of a read-only dataset with no master DB
854 } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
855 return 0; // already reached this point for sure
856 }
857
858 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
859 if ( $pos->getGTIDs() ) {
860 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
861 $rpos = $this->getReplicaPos();
862 $gtidsWait = $rpos ? MySQLMasterPos::getCommonDomainGTIDs( $pos, $rpos ) : [];
863 if ( !$gtidsWait ) {
864 $this->queryLogger->error(
865 "No GTIDs with the same domain between master ($pos) and replica ($rpos)",
866 $this->getLogContext( [
867 'method' => __METHOD__,
868 ] )
869 );
870
871 return -1; // $pos is from the wrong cluster?
872 }
873 // Wait on the GTID set (MariaDB only)
874 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
875 if ( strpos( $gtidArg, ':' ) !== false ) {
876 // MySQL GTIDs, e.g "source_id:transaction_id"
877 $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
878 } else {
879 // MariaDB GTIDs, e.g."domain:server:sequence"
880 $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
881 }
882 } else {
883 // Wait on the binlog coordinates
884 $encFile = $this->addQuotes( $pos->getLogFile() );
885 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT] );
886 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
887 }
888
889 list( $res, $err ) = $this->executeQuery( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
890 $row = $res ? $this->fetchRow( $res ) : false;
891 if ( !$row ) {
892 throw new DBExpectedError( $this, "Replication wait failed: {$err}" );
893 }
894
895 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
896 $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
897 if ( $status === null ) {
898 if ( !$pos->getGTIDs() ) {
899 // T126436: jobs programmed to wait on master positions might be referencing
900 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
901 // Try to detect this case and treat the replica DB as having reached the given
902 // position (any master switchover already requires that the new master be caught
903 // up before the switch).
904 $replicationPos = $this->getReplicaPos();
905 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
906 $this->lastKnownReplicaPos = $replicationPos;
907 $status = 0;
908 }
909 }
910 } elseif ( $status >= 0 ) {
911 // Remember that this position was reached to save queries next time
912 $this->lastKnownReplicaPos = $pos;
913 }
914
915 return $status;
916 }
917
918 /**
919 * Get the position of the master from SHOW SLAVE STATUS
920 *
921 * @return MySQLMasterPos|bool
922 */
923 public function getReplicaPos() {
924 $now = microtime( true ); // as-of-time *before* fetching GTID variables
925
926 if ( $this->useGTIDs() ) {
927 // Try to use GTIDs, fallbacking to binlog positions if not possible
928 $data = $this->getServerGTIDs( __METHOD__ );
929 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
930 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
931 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
932 return new MySQLMasterPos( $data[$name], $now );
933 }
934 }
935 }
936
937 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__ );
938 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
939 return new MySQLMasterPos(
940 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
941 $now
942 );
943 }
944
945 return false;
946 }
947
948 /**
949 * Get the position of the master from SHOW MASTER STATUS
950 *
951 * @return MySQLMasterPos|bool
952 */
953 public function getMasterPos() {
954 $now = microtime( true ); // as-of-time *before* fetching GTID variables
955
956 $pos = false;
957 if ( $this->useGTIDs() ) {
958 // Try to use GTIDs, fallbacking to binlog positions if not possible
959 $data = $this->getServerGTIDs( __METHOD__ );
960 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
961 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
962 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
963 $pos = new MySQLMasterPos( $data[$name], $now );
964 break;
965 }
966 }
967 // Filter domains that are inactive or not relevant to the session
968 if ( $pos ) {
969 $pos->setActiveOriginServerId( $this->getServerId() );
970 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
971 if ( isset( $data['gtid_domain_id'] ) ) {
972 $pos->setActiveDomain( $data['gtid_domain_id'] );
973 }
974 }
975 }
976
977 if ( !$pos ) {
978 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__ );
979 if ( $data && strlen( $data['File'] ) ) {
980 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
981 }
982 }
983
984 return $pos;
985 }
986
987 /**
988 * @return int
989 * @throws DBQueryError If the variable doesn't exist for some reason
990 */
991 protected function getServerId() {
992 $fname = __METHOD__;
993 return $this->srvCache->getWithSetCallback(
994 $this->srvCache->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
995 self::SERVER_ID_CACHE_TTL,
996 function () use ( $fname ) {
997 $flags = self::QUERY_IGNORE_DBO_TRX;
998 $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
999
1000 return intval( $this->fetchObject( $res )->id );
1001 }
1002 );
1003 }
1004
1005 /**
1006 * @return string|null
1007 */
1008 protected function getServerUUID() {
1009 $fname = __METHOD__;
1010 return $this->srvCache->getWithSetCallback(
1011 $this->srvCache->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1012 self::SERVER_ID_CACHE_TTL,
1013 function () use ( $fname ) {
1014 $flags = self::QUERY_IGNORE_DBO_TRX;
1015 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
1016 $row = $this->fetchObject( $res );
1017
1018 return $row ? $row->Value : null;
1019 }
1020 );
1021 }
1022
1023 /**
1024 * @param string $fname
1025 * @return string[]
1026 */
1027 protected function getServerGTIDs( $fname = __METHOD__ ) {
1028 $map = [];
1029
1030 $flags = self::QUERY_IGNORE_DBO_TRX;
1031 // Get global-only variables like gtid_executed
1032 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
1033 foreach ( $res as $row ) {
1034 $map[$row->Variable_name] = $row->Value;
1035 }
1036 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1037 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
1038 foreach ( $res as $row ) {
1039 $map[$row->Variable_name] = $row->Value;
1040 }
1041
1042 return $map;
1043 }
1044
1045 /**
1046 * @param string $role One of "MASTER"/"SLAVE"
1047 * @param string $fname
1048 * @return string[] Latest available server status row
1049 */
1050 protected function getServerRoleStatus( $role, $fname = __METHOD__ ) {
1051 $flags = self::QUERY_IGNORE_DBO_TRX;
1052
1053 return $this->query( "SHOW $role STATUS", $fname, $flags )->fetchRow() ?: [];
1054 }
1055
1056 public function serverIsReadOnly() {
1057 // Avoid SHOW to avoid internal temporary tables
1058 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS;
1059 $res = $this->query( "SELECT @@GLOBAL.read_only AS Value", __METHOD__, $flags );
1060 $row = $this->fetchObject( $res );
1061
1062 return $row ? (bool)$row->Value : false;
1063 }
1064
1065 /**
1066 * @param string $index
1067 * @return string
1068 */
1069 function useIndexClause( $index ) {
1070 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1071 }
1072
1073 /**
1074 * @param string $index
1075 * @return string
1076 */
1077 function ignoreIndexClause( $index ) {
1078 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1079 }
1080
1081 /**
1082 * @return string
1083 */
1084 public function getSoftwareLink() {
1085 // MariaDB includes its name in its version string; this is how MariaDB's version of
1086 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1087 // in libmysql/libmysql.c).
1088 $version = $this->getServerVersion();
1089 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
1090 return '[{{int:version-db-mariadb-url}} MariaDB]';
1091 }
1092
1093 // Percona Server's version suffix is not very distinctive, and @@version_comment
1094 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1095 // (Even Percona's version of mysql doesn't try to make the distinction.)
1096 return '[{{int:version-db-mysql-url}} MySQL]';
1097 }
1098
1099 /**
1100 * @return string
1101 */
1102 public function getServerVersion() {
1103 $cache = $this->srvCache;
1104 $fname = __METHOD__;
1105
1106 return $cache->getWithSetCallback(
1107 $cache->makeGlobalKey( 'mysql-server-version', $this->getServer() ),
1108 $cache::TTL_HOUR,
1109 function () use ( $fname ) {
1110 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1111 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1112 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1113 return $this->selectField( '', 'VERSION()', '', $fname );
1114 }
1115 );
1116 }
1117
1118 /**
1119 * @param array $options
1120 */
1121 public function setSessionOptions( array $options ) {
1122 if ( isset( $options['connTimeout'] ) ) {
1123 $flags = self::QUERY_IGNORE_DBO_TRX;
1124 $timeout = (int)$options['connTimeout'];
1125 $this->query( "SET net_read_timeout=$timeout", __METHOD__, $flags );
1126 $this->query( "SET net_write_timeout=$timeout", __METHOD__, $flags );
1127 }
1128 }
1129
1130 /**
1131 * @param string &$sql
1132 * @param string &$newLine
1133 * @return bool
1134 */
1135 public function streamStatementEnd( &$sql, &$newLine ) {
1136 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1137 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1138 $this->delimiter = $m[1];
1139 $newLine = '';
1140 }
1141
1142 return parent::streamStatementEnd( $sql, $newLine );
1143 }
1144
1145 /**
1146 * Check to see if a named lock is available. This is non-blocking.
1147 *
1148 * @param string $lockName Name of lock to poll
1149 * @param string $method Name of method calling us
1150 * @return bool
1151 * @since 1.20
1152 */
1153 public function lockIsFree( $lockName, $method ) {
1154 if ( !parent::lockIsFree( $lockName, $method ) ) {
1155 return false; // already held
1156 }
1157
1158 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1159
1160 $flags = self::QUERY_IGNORE_DBO_TRX;
1161 $res = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method, $flags );
1162 $row = $this->fetchObject( $res );
1163
1164 return ( $row->lockstatus == 1 );
1165 }
1166
1167 /**
1168 * @param string $lockName
1169 * @param string $method
1170 * @param int $timeout
1171 * @return bool
1172 */
1173 public function lock( $lockName, $method, $timeout = 5 ) {
1174 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1175
1176 $flags = self::QUERY_IGNORE_DBO_TRX;
1177 $res = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method, $flags );
1178 $row = $this->fetchObject( $res );
1179
1180 if ( $row->lockstatus == 1 ) {
1181 parent::lock( $lockName, $method, $timeout ); // record
1182 return true;
1183 }
1184
1185 $this->queryLogger->info( __METHOD__ . " failed to acquire lock '{lockname}'",
1186 [ 'lockname' => $lockName ] );
1187
1188 return false;
1189 }
1190
1191 /**
1192 * FROM MYSQL DOCS:
1193 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1194 * @param string $lockName
1195 * @param string $method
1196 * @return bool
1197 */
1198 public function unlock( $lockName, $method ) {
1199 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1200
1201 $flags = self::QUERY_IGNORE_DBO_TRX;
1202 $res = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method, $flags );
1203 $row = $this->fetchObject( $res );
1204
1205 if ( $row->lockstatus == 1 ) {
1206 parent::unlock( $lockName, $method ); // record
1207 return true;
1208 }
1209
1210 $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
1211
1212 return false;
1213 }
1214
1215 private function makeLockName( $lockName ) {
1216 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1217 // Newer version enforce a 64 char length limit.
1218 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1219 }
1220
1221 public function namedLocksEnqueue() {
1222 return true;
1223 }
1224
1225 public function tableLocksHaveTransactionScope() {
1226 return false; // tied to TCP connection
1227 }
1228
1229 protected function doLockTables( array $read, array $write, $method ) {
1230 $items = [];
1231 foreach ( $write as $table ) {
1232 $items[] = $this->tableName( $table ) . ' WRITE';
1233 }
1234 foreach ( $read as $table ) {
1235 $items[] = $this->tableName( $table ) . ' READ';
1236 }
1237
1238 $sql = "LOCK TABLES " . implode( ',', $items );
1239 $this->query( $sql, $method, self::QUERY_IGNORE_DBO_TRX );
1240
1241 return true;
1242 }
1243
1244 protected function doUnlockTables( $method ) {
1245 $this->query( "UNLOCK TABLES", $method, self::QUERY_IGNORE_DBO_TRX );
1246
1247 return true;
1248 }
1249
1250 /**
1251 * @param bool $value
1252 */
1253 public function setBigSelects( $value = true ) {
1254 if ( $value === 'default' ) {
1255 if ( $this->defaultBigSelects === null ) {
1256 # Function hasn't been called before so it must already be set to the default
1257 return;
1258 } else {
1259 $value = $this->defaultBigSelects;
1260 }
1261 } elseif ( $this->defaultBigSelects === null ) {
1262 $this->defaultBigSelects =
1263 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1264 }
1265 $encValue = $value ? '1' : '0';
1266 $this->query( "SET sql_big_selects=$encValue", __METHOD__, self::QUERY_IGNORE_DBO_TRX );
1267 }
1268
1269 /**
1270 * DELETE where the condition is a join. MySql uses multi-table deletes.
1271 * @param string $delTable
1272 * @param string $joinTable
1273 * @param string $delVar
1274 * @param string $joinVar
1275 * @param array|string $conds
1276 * @param bool|string $fname
1277 * @throws DBUnexpectedError
1278 */
1279 public function deleteJoin(
1280 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1281 ) {
1282 if ( !$conds ) {
1283 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1284 }
1285
1286 $delTable = $this->tableName( $delTable );
1287 $joinTable = $this->tableName( $joinTable );
1288 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1289
1290 if ( $conds != '*' ) {
1291 $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1292 }
1293
1294 $this->query( $sql, $fname );
1295 }
1296
1297 public function upsert(
1298 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1299 ) {
1300 if ( $rows === [] ) {
1301 return true; // nothing to do
1302 }
1303
1304 if ( !is_array( reset( $rows ) ) ) {
1305 $rows = [ $rows ];
1306 }
1307
1308 $table = $this->tableName( $table );
1309 $columns = array_keys( $rows[0] );
1310
1311 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1312 $rowTuples = [];
1313 foreach ( $rows as $row ) {
1314 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1315 }
1316 $sql .= implode( ',', $rowTuples );
1317 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
1318
1319 $this->query( $sql, $fname );
1320
1321 return true;
1322 }
1323
1324 /**
1325 * Determines how long the server has been up
1326 *
1327 * @return int
1328 */
1329 public function getServerUptime() {
1330 $vars = $this->getMysqlStatus( 'Uptime' );
1331
1332 return (int)$vars['Uptime'];
1333 }
1334
1335 /**
1336 * Determines if the last failure was due to a deadlock
1337 *
1338 * @return bool
1339 */
1340 public function wasDeadlock() {
1341 return $this->lastErrno() == 1213;
1342 }
1343
1344 /**
1345 * Determines if the last failure was due to a lock timeout
1346 *
1347 * @return bool
1348 */
1349 public function wasLockTimeout() {
1350 return $this->lastErrno() == 1205;
1351 }
1352
1353 /**
1354 * Determines if the last failure was due to the database being read-only.
1355 *
1356 * @return bool
1357 */
1358 public function wasReadOnlyError() {
1359 return $this->lastErrno() == 1223 ||
1360 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1361 }
1362
1363 public function wasConnectionError( $errno ) {
1364 return $errno == 2013 || $errno == 2006;
1365 }
1366
1367 protected function wasKnownStatementRollbackError() {
1368 $errno = $this->lastErrno();
1369
1370 if ( $errno === 1205 ) { // lock wait timeout
1371 // Note that this is uncached to avoid stale values of SET is used
1372 $row = $this->selectRow(
1373 false,
1374 [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1375 [],
1376 __METHOD__
1377 );
1378 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1379 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1380 return $row->innodb_rollback_on_timeout ? false : true;
1381 }
1382
1383 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1384 return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
1385 }
1386
1387 /**
1388 * @param string $oldName
1389 * @param string $newName
1390 * @param bool $temporary
1391 * @param string $fname
1392 * @return bool
1393 */
1394 public function duplicateTableStructure(
1395 $oldName, $newName, $temporary = false, $fname = __METHOD__
1396 ) {
1397 $tmp = $temporary ? 'TEMPORARY ' : '';
1398 $newName = $this->addIdentifierQuotes( $newName );
1399 $oldName = $this->addIdentifierQuotes( $oldName );
1400 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1401
1402 return $this->query( $query, $fname, $this::QUERY_PSEUDO_PERMANENT );
1403 }
1404
1405 /**
1406 * List all tables on the database
1407 *
1408 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1409 * @param string $fname Calling function name
1410 * @return array
1411 */
1412 public function listTables( $prefix = null, $fname = __METHOD__ ) {
1413 $result = $this->query( "SHOW TABLES", $fname );
1414
1415 $endArray = [];
1416
1417 foreach ( $result as $table ) {
1418 $vars = get_object_vars( $table );
1419 $table = array_pop( $vars );
1420
1421 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1422 $endArray[] = $table;
1423 }
1424 }
1425
1426 return $endArray;
1427 }
1428
1429 /**
1430 * @param string $tableName
1431 * @param string $fName
1432 * @return bool|IResultWrapper
1433 */
1434 public function dropTable( $tableName, $fName = __METHOD__ ) {
1435 if ( !$this->tableExists( $tableName, $fName ) ) {
1436 return false;
1437 }
1438
1439 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1440 }
1441
1442 /**
1443 * Get status information from SHOW STATUS in an associative array
1444 *
1445 * @param string $which
1446 * @return array
1447 */
1448 private function getMysqlStatus( $which = "%" ) {
1449 $flags = self::QUERY_IGNORE_DBO_TRX;
1450 $res = $this->query( "SHOW STATUS LIKE '{$which}'", __METHOD__, $flags );
1451 $status = [];
1452
1453 foreach ( $res as $row ) {
1454 $status[$row->Variable_name] = $row->Value;
1455 }
1456
1457 return $status;
1458 }
1459
1460 /**
1461 * Lists VIEWs in the database
1462 *
1463 * @param string|null $prefix Only show VIEWs with this prefix, eg.
1464 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1465 * @param string $fname Name of calling function
1466 * @return array
1467 * @since 1.22
1468 */
1469 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1470 // The name of the column containing the name of the VIEW
1471 $propertyName = 'Tables_in_' . $this->getDBname();
1472
1473 // Query for the VIEWS
1474 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1475 $allViews = [];
1476 foreach ( $res as $row ) {
1477 array_push( $allViews, $row->$propertyName );
1478 }
1479
1480 if ( is_null( $prefix ) || $prefix === '' ) {
1481 return $allViews;
1482 }
1483
1484 $filteredViews = [];
1485 foreach ( $allViews as $viewName ) {
1486 // Does the name of this VIEW start with the table-prefix?
1487 if ( strpos( $viewName, $prefix ) === 0 ) {
1488 array_push( $filteredViews, $viewName );
1489 }
1490 }
1491
1492 return $filteredViews;
1493 }
1494
1495 /**
1496 * Differentiates between a TABLE and a VIEW.
1497 *
1498 * @param string $name Name of the TABLE/VIEW to test
1499 * @param string|null $prefix
1500 * @return bool
1501 * @since 1.22
1502 */
1503 public function isView( $name, $prefix = null ) {
1504 return in_array( $name, $this->listViews( $prefix ) );
1505 }
1506
1507 protected function isTransactableQuery( $sql ) {
1508 return parent::isTransactableQuery( $sql ) &&
1509 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1510 }
1511
1512 public function buildStringCast( $field ) {
1513 return "CAST( $field AS BINARY )";
1514 }
1515
1516 /**
1517 * @param string $field Field or column to cast
1518 * @return string
1519 */
1520 public function buildIntegerCast( $field ) {
1521 return 'CAST( ' . $field . ' AS SIGNED )';
1522 }
1523
1524 /*
1525 * @return bool Whether GTID support is used (mockable for testing)
1526 */
1527 protected function useGTIDs() {
1528 return $this->useGTIDs;
1529 }
1530 }
1531
1532 /**
1533 * @deprecated since 1.29
1534 */
1535 class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );