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