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