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