Merge "Add Localisation to the links, add the link to Localisation in Languages...
[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
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 DatabaseBase {
33 /** @var MysqlMasterPos */
34 protected $lastKnownReplicaPos;
35 /** @var string Method to detect replica DB lag */
36 protected $lagDetectionMethod;
37 /** @var array Method to detect replica DB lag */
38 protected $lagDetectionOptions = [];
39 /** @var bool bool Whether to use GTID methods */
40 protected $useGTIDs = false;
41 /** @var string|null */
42 protected $sslKeyPath;
43 /** @var string|null */
44 protected $sslCertPath;
45 /** @var string|null */
46 protected $sslCAPath;
47 /** @var string[]|null */
48 protected $sslCiphers;
49 /** @var string sql_mode value to send on connection */
50 protected $sqlMode;
51 /** @var bool Use experimental UTF-8 transmission encoding */
52 protected $utf8Mode;
53
54 /** @var string|null */
55 private $serverVersion = null;
56
57 /**
58 * Additional $params include:
59 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
60 * pt-heartbeat assumes the table is at heartbeat.heartbeat
61 * and uses UTC timestamps in the heartbeat.ts column.
62 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
63 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
64 * the default behavior. Normally, the heartbeat row with the server
65 * ID of this server's master will be used. Set the "conds" field to
66 * override the query conditions, e.g. ['shard' => 's1'].
67 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
68 * - sslKeyPath : path to key file [default: null]
69 * - sslCertPath : path to certificate file [default: null]
70 * - sslCAPath : parth to certificate authority PEM files [default: null]
71 * - sslCiphers : array list of allowable ciphers [default: null]
72 * @param array $params
73 */
74 function __construct( array $params ) {
75 parent::__construct( $params );
76
77 $this->lagDetectionMethod = isset( $params['lagDetectionMethod'] )
78 ? $params['lagDetectionMethod']
79 : 'Seconds_Behind_Master';
80 $this->lagDetectionOptions = isset( $params['lagDetectionOptions'] )
81 ? $params['lagDetectionOptions']
82 : [];
83 $this->useGTIDs = !empty( $params['useGTIDs' ] );
84 foreach ( [ 'KeyPath', 'CertPath', 'CAPath', 'Ciphers' ] as $name ) {
85 $var = "ssl{$name}";
86 if ( isset( $params[$var] ) ) {
87 $this->$var = $params[$var];
88 }
89 }
90 $this->sqlMode = isset( $params['sqlMode'] ) ? $params['sqlMode'] : '';
91 $this->utf8Mode = !empty( $params['utf8Mode'] );
92 }
93
94 /**
95 * @return string
96 */
97 function getType() {
98 return 'mysql';
99 }
100
101 /**
102 * @param string $server
103 * @param string $user
104 * @param string $password
105 * @param string $dbName
106 * @throws Exception|DBConnectionError
107 * @return bool
108 */
109 function open( $server, $user, $password, $dbName ) {
110 # Close/unset connection handle
111 $this->close();
112
113 $this->mServer = $server;
114 $this->mUser = $user;
115 $this->mPassword = $password;
116 $this->mDBname = $dbName;
117
118 $this->installErrorHandler();
119 try {
120 $this->mConn = $this->mysqlConnect( $this->mServer );
121 } catch ( Exception $ex ) {
122 $this->restoreErrorHandler();
123 throw $ex;
124 }
125 $error = $this->restoreErrorHandler();
126
127 # Always log connection errors
128 if ( !$this->mConn ) {
129 if ( !$error ) {
130 $error = $this->lastError();
131 }
132 $this->queryLogger->error(
133 "Error connecting to {db_server}: {error}",
134 $this->getLogContext( [
135 'method' => __METHOD__,
136 'error' => $error,
137 ] )
138 );
139 $this->queryLogger->debug( "DB connection error\n" .
140 "Server: $server, User: $user, Password: " .
141 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
142
143 $this->reportConnectionError( $error );
144 }
145
146 if ( $dbName != '' ) {
147 MediaWiki\suppressWarnings();
148 $success = $this->selectDB( $dbName );
149 MediaWiki\restoreWarnings();
150 if ( !$success ) {
151 $this->queryLogger->error(
152 "Error selecting database {db_name} on server {db_server}",
153 $this->getLogContext( [
154 'method' => __METHOD__,
155 ] )
156 );
157 $this->queryLogger->debug(
158 "Error selecting database $dbName on server {$this->mServer}" );
159
160 $this->reportConnectionError( "Error selecting database $dbName" );
161 }
162 }
163
164 // Tell the server what we're communicating with
165 if ( !$this->connectInitCharset() ) {
166 $this->reportConnectionError( "Error setting character set" );
167 }
168
169 // Abstract over any insane MySQL defaults
170 $set = [ 'group_concat_max_len = 262144' ];
171 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
172 if ( is_string( $this->sqlMode ) ) {
173 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode );
174 }
175 // Set any custom settings defined by site config
176 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
177 foreach ( $this->mSessionVars as $var => $val ) {
178 // Escape strings but not numbers to avoid MySQL complaining
179 if ( !is_int( $val ) && !is_float( $val ) ) {
180 $val = $this->addQuotes( $val );
181 }
182 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
183 }
184
185 if ( $set ) {
186 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
187 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
188 if ( !$success ) {
189 $this->queryLogger->error(
190 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
191 $this->getLogContext( [
192 'method' => __METHOD__,
193 ] )
194 );
195 $this->reportConnectionError(
196 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
197 }
198 }
199
200 $this->mOpened = true;
201
202 return true;
203 }
204
205 /**
206 * Set the character set information right after connection
207 * @return bool
208 */
209 protected function connectInitCharset() {
210 if ( $this->utf8Mode ) {
211 // Tell the server we're communicating with it in UTF-8.
212 // This may engage various charset conversions.
213 return $this->mysqlSetCharset( 'utf8' );
214 } else {
215 return $this->mysqlSetCharset( 'binary' );
216 }
217 }
218
219 /**
220 * Open a connection to a MySQL server
221 *
222 * @param string $realServer
223 * @return mixed Raw connection
224 * @throws DBConnectionError
225 */
226 abstract protected function mysqlConnect( $realServer );
227
228 /**
229 * Set the character set of the MySQL link
230 *
231 * @param string $charset
232 * @return bool
233 */
234 abstract protected function mysqlSetCharset( $charset );
235
236 /**
237 * @param ResultWrapper|resource $res
238 * @throws DBUnexpectedError
239 */
240 function freeResult( $res ) {
241 if ( $res instanceof ResultWrapper ) {
242 $res = $res->result;
243 }
244 MediaWiki\suppressWarnings();
245 $ok = $this->mysqlFreeResult( $res );
246 MediaWiki\restoreWarnings();
247 if ( !$ok ) {
248 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
249 }
250 }
251
252 /**
253 * Free result memory
254 *
255 * @param resource $res Raw result
256 * @return bool
257 */
258 abstract protected function mysqlFreeResult( $res );
259
260 /**
261 * @param ResultWrapper|resource $res
262 * @return stdClass|bool
263 * @throws DBUnexpectedError
264 */
265 function fetchObject( $res ) {
266 if ( $res instanceof ResultWrapper ) {
267 $res = $res->result;
268 }
269 MediaWiki\suppressWarnings();
270 $row = $this->mysqlFetchObject( $res );
271 MediaWiki\restoreWarnings();
272
273 $errno = $this->lastErrno();
274 // Unfortunately, mysql_fetch_object does not reset the last errno.
275 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
276 // these are the only errors mysql_fetch_object can cause.
277 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
278 if ( $errno == 2000 || $errno == 2013 ) {
279 throw new DBUnexpectedError(
280 $this,
281 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
282 );
283 }
284
285 return $row;
286 }
287
288 /**
289 * Fetch a result row as an object
290 *
291 * @param resource $res Raw result
292 * @return stdClass
293 */
294 abstract protected function mysqlFetchObject( $res );
295
296 /**
297 * @param ResultWrapper|resource $res
298 * @return array|bool
299 * @throws DBUnexpectedError
300 */
301 function fetchRow( $res ) {
302 if ( $res instanceof ResultWrapper ) {
303 $res = $res->result;
304 }
305 MediaWiki\suppressWarnings();
306 $row = $this->mysqlFetchArray( $res );
307 MediaWiki\restoreWarnings();
308
309 $errno = $this->lastErrno();
310 // Unfortunately, mysql_fetch_array does not reset the last errno.
311 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
312 // these are the only errors mysql_fetch_array can cause.
313 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
314 if ( $errno == 2000 || $errno == 2013 ) {
315 throw new DBUnexpectedError(
316 $this,
317 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
318 );
319 }
320
321 return $row;
322 }
323
324 /**
325 * Fetch a result row as an associative and numeric array
326 *
327 * @param resource $res Raw result
328 * @return array
329 */
330 abstract protected function mysqlFetchArray( $res );
331
332 /**
333 * @throws DBUnexpectedError
334 * @param ResultWrapper|resource $res
335 * @return int
336 */
337 function numRows( $res ) {
338 if ( $res instanceof ResultWrapper ) {
339 $res = $res->result;
340 }
341 MediaWiki\suppressWarnings();
342 $n = $this->mysqlNumRows( $res );
343 MediaWiki\restoreWarnings();
344
345 // Unfortunately, mysql_num_rows does not reset the last errno.
346 // We are not checking for any errors here, since
347 // these are no errors mysql_num_rows can cause.
348 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
349 // See https://phabricator.wikimedia.org/T44430
350 return $n;
351 }
352
353 /**
354 * Get number of rows in result
355 *
356 * @param resource $res Raw result
357 * @return int
358 */
359 abstract protected function mysqlNumRows( $res );
360
361 /**
362 * @param ResultWrapper|resource $res
363 * @return int
364 */
365 function numFields( $res ) {
366 if ( $res instanceof ResultWrapper ) {
367 $res = $res->result;
368 }
369
370 return $this->mysqlNumFields( $res );
371 }
372
373 /**
374 * Get number of fields in result
375 *
376 * @param resource $res Raw result
377 * @return int
378 */
379 abstract protected function mysqlNumFields( $res );
380
381 /**
382 * @param ResultWrapper|resource $res
383 * @param int $n
384 * @return string
385 */
386 function fieldName( $res, $n ) {
387 if ( $res instanceof ResultWrapper ) {
388 $res = $res->result;
389 }
390
391 return $this->mysqlFieldName( $res, $n );
392 }
393
394 /**
395 * Get the name of the specified field in a result
396 *
397 * @param ResultWrapper|resource $res
398 * @param int $n
399 * @return string
400 */
401 abstract protected function mysqlFieldName( $res, $n );
402
403 /**
404 * mysql_field_type() wrapper
405 * @param ResultWrapper|resource $res
406 * @param int $n
407 * @return string
408 */
409 public function fieldType( $res, $n ) {
410 if ( $res instanceof ResultWrapper ) {
411 $res = $res->result;
412 }
413
414 return $this->mysqlFieldType( $res, $n );
415 }
416
417 /**
418 * Get the type of the specified field in a result
419 *
420 * @param ResultWrapper|resource $res
421 * @param int $n
422 * @return string
423 */
424 abstract protected function mysqlFieldType( $res, $n );
425
426 /**
427 * @param ResultWrapper|resource $res
428 * @param int $row
429 * @return bool
430 */
431 function dataSeek( $res, $row ) {
432 if ( $res instanceof ResultWrapper ) {
433 $res = $res->result;
434 }
435
436 return $this->mysqlDataSeek( $res, $row );
437 }
438
439 /**
440 * Move internal result pointer
441 *
442 * @param ResultWrapper|resource $res
443 * @param int $row
444 * @return bool
445 */
446 abstract protected function mysqlDataSeek( $res, $row );
447
448 /**
449 * @return string
450 */
451 function lastError() {
452 if ( $this->mConn ) {
453 # Even if it's non-zero, it can still be invalid
454 MediaWiki\suppressWarnings();
455 $error = $this->mysqlError( $this->mConn );
456 if ( !$error ) {
457 $error = $this->mysqlError();
458 }
459 MediaWiki\restoreWarnings();
460 } else {
461 $error = $this->mysqlError();
462 }
463 if ( $error ) {
464 $error .= ' (' . $this->mServer . ')';
465 }
466
467 return $error;
468 }
469
470 /**
471 * Returns the text of the error message from previous MySQL operation
472 *
473 * @param resource $conn Raw connection
474 * @return string
475 */
476 abstract protected function mysqlError( $conn = null );
477
478 /**
479 * @param string $table
480 * @param array $uniqueIndexes
481 * @param array $rows
482 * @param string $fname
483 * @return ResultWrapper
484 */
485 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
486 return $this->nativeReplace( $table, $rows, $fname );
487 }
488
489 /**
490 * Estimate rows in dataset
491 * Returns estimated count, based on EXPLAIN output
492 * Takes same arguments as Database::select()
493 *
494 * @param string|array $table
495 * @param string|array $vars
496 * @param string|array $conds
497 * @param string $fname
498 * @param string|array $options
499 * @return bool|int
500 */
501 public function estimateRowCount( $table, $vars = '*', $conds = '',
502 $fname = __METHOD__, $options = []
503 ) {
504 $options['EXPLAIN'] = true;
505 $res = $this->select( $table, $vars, $conds, $fname, $options );
506 if ( $res === false ) {
507 return false;
508 }
509 if ( !$this->numRows( $res ) ) {
510 return 0;
511 }
512
513 $rows = 1;
514 foreach ( $res as $plan ) {
515 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
516 }
517
518 return (int)$rows;
519 }
520
521 /**
522 * @param string $table
523 * @param string $field
524 * @return bool|MySQLField
525 */
526 function fieldInfo( $table, $field ) {
527 $table = $this->tableName( $table );
528 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
529 if ( !$res ) {
530 return false;
531 }
532 $n = $this->mysqlNumFields( $res->result );
533 for ( $i = 0; $i < $n; $i++ ) {
534 $meta = $this->mysqlFetchField( $res->result, $i );
535 if ( $field == $meta->name ) {
536 return new MySQLField( $meta );
537 }
538 }
539
540 return false;
541 }
542
543 /**
544 * Get column information from a result
545 *
546 * @param resource $res Raw result
547 * @param int $n
548 * @return stdClass
549 */
550 abstract protected function mysqlFetchField( $res, $n );
551
552 /**
553 * Get information about an index into an object
554 * Returns false if the index does not exist
555 *
556 * @param string $table
557 * @param string $index
558 * @param string $fname
559 * @return bool|array|null False or null on failure
560 */
561 function indexInfo( $table, $index, $fname = __METHOD__ ) {
562 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
563 # SHOW INDEX should work for 3.x and up:
564 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
565 $table = $this->tableName( $table );
566 $index = $this->indexName( $index );
567
568 $sql = 'SHOW INDEX FROM ' . $table;
569 $res = $this->query( $sql, $fname );
570
571 if ( !$res ) {
572 return null;
573 }
574
575 $result = [];
576
577 foreach ( $res as $row ) {
578 if ( $row->Key_name == $index ) {
579 $result[] = $row;
580 }
581 }
582
583 return empty( $result ) ? false : $result;
584 }
585
586 /**
587 * @param string $s
588 * @return string
589 */
590 function strencode( $s ) {
591 return $this->mysqlRealEscapeString( $s );
592 }
593
594 /**
595 * @param string $s
596 * @return mixed
597 */
598 abstract protected function mysqlRealEscapeString( $s );
599
600 /**
601 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
602 *
603 * @param string $s
604 * @return string
605 */
606 public function addIdentifierQuotes( $s ) {
607 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
608 // Remove NUL bytes and escape backticks by doubling
609 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
610 }
611
612 /**
613 * @param string $name
614 * @return bool
615 */
616 public function isQuotedIdentifier( $name ) {
617 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
618 }
619
620 function getLag() {
621 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
622 return $this->getLagFromPtHeartbeat();
623 } else {
624 return $this->getLagFromSlaveStatus();
625 }
626 }
627
628 /**
629 * @return string
630 */
631 protected function getLagDetectionMethod() {
632 return $this->lagDetectionMethod;
633 }
634
635 /**
636 * @return bool|int
637 */
638 protected function getLagFromSlaveStatus() {
639 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
640 $row = $res ? $res->fetchObject() : false;
641 if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
642 return intval( $row->Seconds_Behind_Master );
643 }
644
645 return false;
646 }
647
648 /**
649 * @return bool|float
650 */
651 protected function getLagFromPtHeartbeat() {
652 $options = $this->lagDetectionOptions;
653
654 if ( isset( $options['conds'] ) ) {
655 // Best method for multi-DC setups: use logical channel names
656 $data = $this->getHeartbeatData( $options['conds'] );
657 } else {
658 // Standard method: use master server ID (works with stock pt-heartbeat)
659 $masterInfo = $this->getMasterServerInfo();
660 if ( !$masterInfo ) {
661 $this->queryLogger->error(
662 "Unable to query master of {db_server} for server ID",
663 $this->getLogContext( [
664 'method' => __METHOD__
665 ] )
666 );
667
668 return false; // could not get master server ID
669 }
670
671 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
672 $data = $this->getHeartbeatData( $conds );
673 }
674
675 list( $time, $nowUnix ) = $data;
676 if ( $time !== null ) {
677 // @time is in ISO format like "2015-09-25T16:48:10.000510"
678 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
679 $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
680
681 return max( $nowUnix - $timeUnix, 0.0 );
682 }
683
684 $this->queryLogger->error(
685 "Unable to find pt-heartbeat row for {db_server}",
686 $this->getLogContext( [
687 'method' => __METHOD__
688 ] )
689 );
690
691 return false;
692 }
693
694 protected function getMasterServerInfo() {
695 $cache = $this->srvCache;
696 $key = $cache->makeGlobalKey(
697 'mysql',
698 'master-info',
699 // Using one key for all cluster replica DBs is preferable
700 $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
701 );
702
703 return $cache->getWithSetCallback(
704 $key,
705 $cache::TTL_INDEFINITE,
706 function () use ( $cache, $key ) {
707 // Get and leave a lock key in place for a short period
708 if ( !$cache->lock( $key, 0, 10 ) ) {
709 return false; // avoid master connection spike slams
710 }
711
712 $conn = $this->getLazyMasterHandle();
713 if ( !$conn ) {
714 return false; // something is misconfigured
715 }
716
717 // Connect to and query the master; catch errors to avoid outages
718 try {
719 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__ );
720 $row = $res ? $res->fetchObject() : false;
721 $id = $row ? (int)$row->id : 0;
722 } catch ( DBError $e ) {
723 $id = 0;
724 }
725
726 // Cache the ID if it was retrieved
727 return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
728 }
729 );
730 }
731
732 /**
733 * @param array $conds WHERE clause conditions to find a row
734 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
735 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
736 */
737 protected function getHeartbeatData( array $conds ) {
738 $whereSQL = $this->makeList( $conds, self::LIST_AND );
739 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
740 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
741 // percision field is not supported in MySQL <= 5.5.
742 $res = $this->query(
743 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
744 );
745 $row = $res ? $res->fetchObject() : false;
746
747 return [ $row ? $row->ts : null, microtime( true ) ];
748 }
749
750 public function getApproximateLagStatus() {
751 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
752 // Disable caching since this is fast enough and we don't wan't
753 // to be *too* pessimistic by having both the cache TTL and the
754 // pt-heartbeat interval count as lag in getSessionLagStatus()
755 return parent::getApproximateLagStatus();
756 }
757
758 $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
759 $approxLag = $this->srvCache->get( $key );
760 if ( !$approxLag ) {
761 $approxLag = parent::getApproximateLagStatus();
762 $this->srvCache->set( $key, $approxLag, 1 );
763 }
764
765 return $approxLag;
766 }
767
768 function masterPosWait( DBMasterPos $pos, $timeout ) {
769 if ( !( $pos instanceof MySQLMasterPos ) ) {
770 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
771 }
772
773 if ( $this->getLBInfo( 'is static' ) === true ) {
774 return 0; // this is a copy of a read-only dataset with no master DB
775 } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
776 return 0; // already reached this point for sure
777 }
778
779 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
780 if ( $this->useGTIDs && $pos->gtids ) {
781 // Wait on the GTID set (MariaDB only)
782 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids ) );
783 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
784 } else {
785 // Wait on the binlog coordinates
786 $encFile = $this->addQuotes( $pos->file );
787 $encPos = intval( $pos->pos );
788 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
789 }
790
791 $row = $res ? $this->fetchRow( $res ) : false;
792 if ( !$row ) {
793 throw new DBExpectedError( $this, "Failed to query MASTER_POS_WAIT()" );
794 }
795
796 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
797 $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
798 if ( $status === null ) {
799 // T126436: jobs programmed to wait on master positions might be referencing binlogs
800 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
801 // to detect this and treat the replica DB as having reached the position; a proper master
802 // switchover already requires that the new master be caught up before the switch.
803 $replicationPos = $this->getSlavePos();
804 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
805 $this->lastKnownReplicaPos = $replicationPos;
806 $status = 0;
807 }
808 } elseif ( $status >= 0 ) {
809 // Remember that this position was reached to save queries next time
810 $this->lastKnownReplicaPos = $pos;
811 }
812
813 return $status;
814 }
815
816 /**
817 * Get the position of the master from SHOW SLAVE STATUS
818 *
819 * @return MySQLMasterPos|bool
820 */
821 function getSlavePos() {
822 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
823 $row = $this->fetchObject( $res );
824
825 if ( $row ) {
826 $pos = isset( $row->Exec_master_log_pos )
827 ? $row->Exec_master_log_pos
828 : $row->Exec_Master_Log_Pos;
829 // Also fetch the last-applied GTID set (MariaDB)
830 if ( $this->useGTIDs ) {
831 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__ );
832 $gtidRow = $this->fetchObject( $res );
833 $gtidSet = $gtidRow ? $gtidRow->Value : '';
834 } else {
835 $gtidSet = '';
836 }
837
838 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos, $gtidSet );
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', __METHOD__ );
851 $row = $this->fetchObject( $res );
852
853 if ( $row ) {
854 // Also fetch the last-written GTID set (MariaDB)
855 if ( $this->useGTIDs ) {
856 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__ );
857 $gtidRow = $this->fetchObject( $res );
858 $gtidSet = $gtidRow ? $gtidRow->Value : '';
859 } else {
860 $gtidSet = '';
861 }
862
863 return new MySQLMasterPos( $row->File, $row->Position, $gtidSet );
864 } else {
865 return false;
866 }
867 }
868
869 public function serverIsReadOnly() {
870 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__ );
871 $row = $this->fetchObject( $res );
872
873 return $row ? ( strtolower( $row->Value ) === 'on' ) : false;
874 }
875
876 /**
877 * @param string $index
878 * @return string
879 */
880 function useIndexClause( $index ) {
881 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
882 }
883
884 /**
885 * @param string $index
886 * @return string
887 */
888 function ignoreIndexClause( $index ) {
889 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
890 }
891
892 /**
893 * @return string
894 */
895 function lowPriorityOption() {
896 return 'LOW_PRIORITY';
897 }
898
899 /**
900 * @return string
901 */
902 public function getSoftwareLink() {
903 // MariaDB includes its name in its version string; this is how MariaDB's version of
904 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
905 // in libmysql/libmysql.c).
906 $version = $this->getServerVersion();
907 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
908 return '[{{int:version-db-mariadb-url}} MariaDB]';
909 }
910
911 // Percona Server's version suffix is not very distinctive, and @@version_comment
912 // doesn't give the necessary info for source builds, so assume the server is MySQL.
913 // (Even Percona's version of mysql doesn't try to make the distinction.)
914 return '[{{int:version-db-mysql-url}} MySQL]';
915 }
916
917 /**
918 * @return string
919 */
920 public function getServerVersion() {
921 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
922 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
923 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
924 if ( $this->serverVersion === null ) {
925 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
926 }
927 return $this->serverVersion;
928 }
929
930 /**
931 * @param array $options
932 */
933 public function setSessionOptions( array $options ) {
934 if ( isset( $options['connTimeout'] ) ) {
935 $timeout = (int)$options['connTimeout'];
936 $this->query( "SET net_read_timeout=$timeout" );
937 $this->query( "SET net_write_timeout=$timeout" );
938 }
939 }
940
941 /**
942 * @param string $sql
943 * @param string $newLine
944 * @return bool
945 */
946 public function streamStatementEnd( &$sql, &$newLine ) {
947 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
948 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
949 $this->delimiter = $m[1];
950 $newLine = '';
951 }
952
953 return parent::streamStatementEnd( $sql, $newLine );
954 }
955
956 /**
957 * Check to see if a named lock is available. This is non-blocking.
958 *
959 * @param string $lockName Name of lock to poll
960 * @param string $method Name of method calling us
961 * @return bool
962 * @since 1.20
963 */
964 public function lockIsFree( $lockName, $method ) {
965 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
966 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
967 $row = $this->fetchObject( $result );
968
969 return ( $row->lockstatus == 1 );
970 }
971
972 /**
973 * @param string $lockName
974 * @param string $method
975 * @param int $timeout
976 * @return bool
977 */
978 public function lock( $lockName, $method, $timeout = 5 ) {
979 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
980 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
981 $row = $this->fetchObject( $result );
982
983 if ( $row->lockstatus == 1 ) {
984 parent::lock( $lockName, $method, $timeout ); // record
985 return true;
986 }
987
988 $this->queryLogger->debug( __METHOD__ . " failed to acquire lock\n" );
989
990 return false;
991 }
992
993 /**
994 * FROM MYSQL DOCS:
995 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
996 * @param string $lockName
997 * @param string $method
998 * @return bool
999 */
1000 public function unlock( $lockName, $method ) {
1001 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
1002 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
1003 $row = $this->fetchObject( $result );
1004
1005 if ( $row->lockstatus == 1 ) {
1006 parent::unlock( $lockName, $method ); // record
1007 return true;
1008 }
1009
1010 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1011
1012 return false;
1013 }
1014
1015 private function makeLockName( $lockName ) {
1016 // http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1017 // Newer version enforce a 64 char length limit.
1018 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1019 }
1020
1021 public function namedLocksEnqueue() {
1022 return true;
1023 }
1024
1025 /**
1026 * @param array $read
1027 * @param array $write
1028 * @param string $method
1029 * @param bool $lowPriority
1030 * @return bool
1031 */
1032 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1033 $items = [];
1034
1035 foreach ( $write as $table ) {
1036 $tbl = $this->tableName( $table ) .
1037 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
1038 ' WRITE';
1039 $items[] = $tbl;
1040 }
1041 foreach ( $read as $table ) {
1042 $items[] = $this->tableName( $table ) . ' READ';
1043 }
1044 $sql = "LOCK TABLES " . implode( ',', $items );
1045 $this->query( $sql, $method );
1046
1047 return true;
1048 }
1049
1050 /**
1051 * @param string $method
1052 * @return bool
1053 */
1054 public function unlockTables( $method ) {
1055 $this->query( "UNLOCK TABLES", $method );
1056
1057 return true;
1058 }
1059
1060 /**
1061 * @param bool $value
1062 */
1063 public function setBigSelects( $value = true ) {
1064 if ( $value === 'default' ) {
1065 if ( $this->mDefaultBigSelects === null ) {
1066 # Function hasn't been called before so it must already be set to the default
1067 return;
1068 } else {
1069 $value = $this->mDefaultBigSelects;
1070 }
1071 } elseif ( $this->mDefaultBigSelects === null ) {
1072 $this->mDefaultBigSelects =
1073 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1074 }
1075 $encValue = $value ? '1' : '0';
1076 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
1077 }
1078
1079 /**
1080 * DELETE where the condition is a join. MySql uses multi-table deletes.
1081 * @param string $delTable
1082 * @param string $joinTable
1083 * @param string $delVar
1084 * @param string $joinVar
1085 * @param array|string $conds
1086 * @param bool|string $fname
1087 * @throws DBUnexpectedError
1088 * @return bool|ResultWrapper
1089 */
1090 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
1091 if ( !$conds ) {
1092 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1093 }
1094
1095 $delTable = $this->tableName( $delTable );
1096 $joinTable = $this->tableName( $joinTable );
1097 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1098
1099 if ( $conds != '*' ) {
1100 $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1101 }
1102
1103 return $this->query( $sql, $fname );
1104 }
1105
1106 /**
1107 * @param string $table
1108 * @param array $rows
1109 * @param array $uniqueIndexes
1110 * @param array $set
1111 * @param string $fname
1112 * @return bool
1113 */
1114 public function upsert( $table, array $rows, array $uniqueIndexes,
1115 array $set, $fname = __METHOD__
1116 ) {
1117 if ( !count( $rows ) ) {
1118 return true; // nothing to do
1119 }
1120
1121 if ( !is_array( reset( $rows ) ) ) {
1122 $rows = [ $rows ];
1123 }
1124
1125 $table = $this->tableName( $table );
1126 $columns = array_keys( $rows[0] );
1127
1128 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1129 $rowTuples = [];
1130 foreach ( $rows as $row ) {
1131 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1132 }
1133 $sql .= implode( ',', $rowTuples );
1134 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
1135
1136 return (bool)$this->query( $sql, $fname );
1137 }
1138
1139 /**
1140 * Determines how long the server has been up
1141 *
1142 * @return int
1143 */
1144 function getServerUptime() {
1145 $vars = $this->getMysqlStatus( 'Uptime' );
1146
1147 return (int)$vars['Uptime'];
1148 }
1149
1150 /**
1151 * Determines if the last failure was due to a deadlock
1152 *
1153 * @return bool
1154 */
1155 function wasDeadlock() {
1156 return $this->lastErrno() == 1213;
1157 }
1158
1159 /**
1160 * Determines if the last failure was due to a lock timeout
1161 *
1162 * @return bool
1163 */
1164 function wasLockTimeout() {
1165 return $this->lastErrno() == 1205;
1166 }
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