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