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