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