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