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