Added autopatrol parameter to MarkPatrolled and MarkPatrolledComplete hooks
[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 * @param string $s
577 * @return mixed
578 */
579 abstract protected function mysqlRealEscapeString( $s );
580
581 /**
582 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
583 *
584 * @param string $s
585 * @return string
586 */
587 public function addIdentifierQuotes( $s ) {
588 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
589 // Remove NUL bytes and escape backticks by doubling
590 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
591 }
592
593 /**
594 * @param string $name
595 * @return bool
596 */
597 public function isQuotedIdentifier( $name ) {
598 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
599 }
600
601 /**
602 * @return bool
603 */
604 function ping() {
605 $ping = $this->mysqlPing();
606 if ( $ping ) {
607 // Connection was good or lost but reconnected...
608 // @note: mysqlnd (php 5.6+) does not support this (PHP bug 52561)
609 return true;
610 }
611
612 // Try a full disconnect/reconnect cycle if ping() failed
613 $this->closeConnection();
614 $this->mOpened = false;
615 $this->mConn = false;
616 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
617
618 return true;
619 }
620
621 /**
622 * Ping a server connection or reconnect if there is no connection
623 *
624 * @return bool
625 */
626 abstract protected function mysqlPing();
627
628 /**
629 * Returns slave lag.
630 *
631 * This will do a SHOW SLAVE STATUS
632 *
633 * @return int
634 */
635 function getLag() {
636 if ( $this->lagDetectionMethod === 'pt-heartbeat' ) {
637 return $this->getLagFromPtHeartbeat();
638 } else {
639 return $this->getLagFromSlaveStatus();
640 }
641 }
642
643 /**
644 * @return bool|int
645 */
646 protected function getLagFromSlaveStatus() {
647 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
648 $row = $res ? $res->fetchObject() : false;
649 if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
650 return intval( $row->Seconds_Behind_Master );
651 }
652
653 return false;
654 }
655
656 /**
657 * @return bool|float
658 */
659 protected function getLagFromPtHeartbeat() {
660 $key = wfMemcKey( 'mysql', 'master-server-id', $this->getServer() );
661 $masterId = intval( $this->srvCache->get( $key ) );
662 if ( !$masterId ) {
663 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
664 $row = $res ? $res->fetchObject() : false;
665 if ( $row && strval( $row->Master_Server_Id ) !== '' ) {
666 $masterId = intval( $row->Master_Server_Id );
667 $this->srvCache->set( $key, $masterId, 30 );
668 }
669 }
670
671 if ( !$masterId ) {
672 return false;
673 }
674
675 $res = $this->query(
676 "SELECT TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6)) AS Lag " .
677 "FROM heartbeat.heartbeat WHERE server_id = $masterId"
678 );
679 $row = $res ? $res->fetchObject() : false;
680 if ( $row ) {
681 return max( floatval( $row->Lag ) / 1e6, 0.0 );
682 }
683
684 return false;
685 }
686
687 /**
688 * Wait for the slave to catch up to a given master position.
689 * @todo Return values for this and base class are rubbish
690 *
691 * @param DBMasterPos|MySQLMasterPos $pos
692 * @param int $timeout The maximum number of seconds to wait for synchronisation
693 * @return int Zero if the slave was past that position already,
694 * greater than zero if we waited for some period of time, less than
695 * zero if we timed out.
696 */
697 function masterPosWait( DBMasterPos $pos, $timeout ) {
698 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
699 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
700 }
701
702 # Commit any open transactions
703 $this->commit( __METHOD__, 'flush' );
704
705 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
706 $encFile = $this->addQuotes( $pos->file );
707 $encPos = intval( $pos->pos );
708 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
709 $res = $this->doQuery( $sql );
710
711 $status = false;
712 if ( $res && $row = $this->fetchRow( $res ) ) {
713 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
714 if ( ctype_digit( $status ) ) { // success
715 $this->lastKnownSlavePos = $pos;
716 }
717 }
718
719 return $status;
720 }
721
722 /**
723 * Get the position of the master from SHOW SLAVE STATUS
724 *
725 * @return MySQLMasterPos|bool
726 */
727 function getSlavePos() {
728 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
729 $row = $this->fetchObject( $res );
730
731 if ( $row ) {
732 $pos = isset( $row->Exec_master_log_pos )
733 ? $row->Exec_master_log_pos
734 : $row->Exec_Master_Log_Pos;
735
736 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
737 } else {
738 return false;
739 }
740 }
741
742 /**
743 * Get the position of the master from SHOW MASTER STATUS
744 *
745 * @return MySQLMasterPos|bool
746 */
747 function getMasterPos() {
748 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
749 $row = $this->fetchObject( $res );
750
751 if ( $row ) {
752 return new MySQLMasterPos( $row->File, $row->Position );
753 } else {
754 return false;
755 }
756 }
757
758 /**
759 * @param string $index
760 * @return string
761 */
762 function useIndexClause( $index ) {
763 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
764 }
765
766 /**
767 * @return string
768 */
769 function lowPriorityOption() {
770 return 'LOW_PRIORITY';
771 }
772
773 /**
774 * @return string
775 */
776 public function getSoftwareLink() {
777 // MariaDB includes its name in its version string; this is how MariaDB's version of
778 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
779 // in libmysql/libmysql.c).
780 $version = $this->getServerVersion();
781 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
782 return '[{{int:version-db-mariadb-url}} MariaDB]';
783 }
784
785 // Percona Server's version suffix is not very distinctive, and @@version_comment
786 // doesn't give the necessary info for source builds, so assume the server is MySQL.
787 // (Even Percona's version of mysql doesn't try to make the distinction.)
788 return '[{{int:version-db-mysql-url}} MySQL]';
789 }
790
791 /**
792 * @return string
793 */
794 public function getServerVersion() {
795 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
796 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
797 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
798 if ( $this->serverVersion === null ) {
799 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
800 }
801 return $this->serverVersion;
802 }
803
804 /**
805 * @param array $options
806 */
807 public function setSessionOptions( array $options ) {
808 if ( isset( $options['connTimeout'] ) ) {
809 $timeout = (int)$options['connTimeout'];
810 $this->query( "SET net_read_timeout=$timeout" );
811 $this->query( "SET net_write_timeout=$timeout" );
812 }
813 }
814
815 /**
816 * @param string $sql
817 * @param string $newLine
818 * @return bool
819 */
820 public function streamStatementEnd( &$sql, &$newLine ) {
821 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
822 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
823 $this->delimiter = $m[1];
824 $newLine = '';
825 }
826
827 return parent::streamStatementEnd( $sql, $newLine );
828 }
829
830 /**
831 * Check to see if a named lock is available. This is non-blocking.
832 *
833 * @param string $lockName Name of lock to poll
834 * @param string $method Name of method calling us
835 * @return bool
836 * @since 1.20
837 */
838 public function lockIsFree( $lockName, $method ) {
839 $lockName = $this->addQuotes( $lockName );
840 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
841 $row = $this->fetchObject( $result );
842
843 return ( $row->lockstatus == 1 );
844 }
845
846 /**
847 * @param string $lockName
848 * @param string $method
849 * @param int $timeout
850 * @return bool
851 */
852 public function lock( $lockName, $method, $timeout = 5 ) {
853 $lockName = $this->addQuotes( $lockName );
854 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
855 $row = $this->fetchObject( $result );
856
857 if ( $row->lockstatus == 1 ) {
858 return true;
859 } else {
860 wfDebug( __METHOD__ . " failed to acquire lock\n" );
861
862 return false;
863 }
864 }
865
866 /**
867 * FROM MYSQL DOCS:
868 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
869 * @param string $lockName
870 * @param string $method
871 * @return bool
872 */
873 public function unlock( $lockName, $method ) {
874 $lockName = $this->addQuotes( $lockName );
875 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
876 $row = $this->fetchObject( $result );
877
878 return ( $row->lockstatus == 1 );
879 }
880
881 public function namedLocksEnqueue() {
882 return true;
883 }
884
885 /**
886 * @param array $read
887 * @param array $write
888 * @param string $method
889 * @param bool $lowPriority
890 * @return bool
891 */
892 public function lockTables( $read, $write, $method, $lowPriority = true ) {
893 $items = array();
894
895 foreach ( $write as $table ) {
896 $tbl = $this->tableName( $table ) .
897 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
898 ' WRITE';
899 $items[] = $tbl;
900 }
901 foreach ( $read as $table ) {
902 $items[] = $this->tableName( $table ) . ' READ';
903 }
904 $sql = "LOCK TABLES " . implode( ',', $items );
905 $this->query( $sql, $method );
906
907 return true;
908 }
909
910 /**
911 * @param string $method
912 * @return bool
913 */
914 public function unlockTables( $method ) {
915 $this->query( "UNLOCK TABLES", $method );
916
917 return true;
918 }
919
920 /**
921 * Get search engine class. All subclasses of this
922 * need to implement this if they wish to use searching.
923 *
924 * @return string
925 */
926 public function getSearchEngine() {
927 return 'SearchMySQL';
928 }
929
930 /**
931 * @param bool $value
932 */
933 public function setBigSelects( $value = true ) {
934 if ( $value === 'default' ) {
935 if ( $this->mDefaultBigSelects === null ) {
936 # Function hasn't been called before so it must already be set to the default
937 return;
938 } else {
939 $value = $this->mDefaultBigSelects;
940 }
941 } elseif ( $this->mDefaultBigSelects === null ) {
942 $this->mDefaultBigSelects =
943 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
944 }
945 $encValue = $value ? '1' : '0';
946 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
947 }
948
949 /**
950 * DELETE where the condition is a join. MySql uses multi-table deletes.
951 * @param string $delTable
952 * @param string $joinTable
953 * @param string $delVar
954 * @param string $joinVar
955 * @param array|string $conds
956 * @param bool|string $fname
957 * @throws DBUnexpectedError
958 * @return bool|ResultWrapper
959 */
960 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
961 if ( !$conds ) {
962 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
963 }
964
965 $delTable = $this->tableName( $delTable );
966 $joinTable = $this->tableName( $joinTable );
967 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
968
969 if ( $conds != '*' ) {
970 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
971 }
972
973 return $this->query( $sql, $fname );
974 }
975
976 /**
977 * @param string $table
978 * @param array $rows
979 * @param array $uniqueIndexes
980 * @param array $set
981 * @param string $fname
982 * @return bool
983 */
984 public function upsert( $table, array $rows, array $uniqueIndexes,
985 array $set, $fname = __METHOD__
986 ) {
987 if ( !count( $rows ) ) {
988 return true; // nothing to do
989 }
990
991 if ( !is_array( reset( $rows ) ) ) {
992 $rows = array( $rows );
993 }
994
995 $table = $this->tableName( $table );
996 $columns = array_keys( $rows[0] );
997
998 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
999 $rowTuples = array();
1000 foreach ( $rows as $row ) {
1001 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1002 }
1003 $sql .= implode( ',', $rowTuples );
1004 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
1005
1006 return (bool)$this->query( $sql, $fname );
1007 }
1008
1009 /**
1010 * Determines how long the server has been up
1011 *
1012 * @return int
1013 */
1014 function getServerUptime() {
1015 $vars = $this->getMysqlStatus( 'Uptime' );
1016
1017 return (int)$vars['Uptime'];
1018 }
1019
1020 /**
1021 * Determines if the last failure was due to a deadlock
1022 *
1023 * @return bool
1024 */
1025 function wasDeadlock() {
1026 return $this->lastErrno() == 1213;
1027 }
1028
1029 /**
1030 * Determines if the last failure was due to a lock timeout
1031 *
1032 * @return bool
1033 */
1034 function wasLockTimeout() {
1035 return $this->lastErrno() == 1205;
1036 }
1037
1038 /**
1039 * Determines if the last query error was something that should be dealt
1040 * with by pinging the connection and reissuing the query
1041 *
1042 * @return bool
1043 */
1044 function wasErrorReissuable() {
1045 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1046 }
1047
1048 /**
1049 * Determines if the last failure was due to the database being read-only.
1050 *
1051 * @return bool
1052 */
1053 function wasReadOnlyError() {
1054 return $this->lastErrno() == 1223 ||
1055 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1056 }
1057
1058 function wasConnectionError( $errno ) {
1059 return $errno == 2013 || $errno == 2006;
1060 }
1061
1062 /**
1063 * Get the underlying binding handle, mConn
1064 *
1065 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1066 * This catches broken callers than catch and ignore disconnection exceptions.
1067 * Unlike checking isOpen(), this is safe to call inside of open().
1068 *
1069 * @return resource|object
1070 * @throws DBUnexpectedError
1071 * @since 1.26
1072 */
1073 protected function getBindingHandle() {
1074 if ( !$this->mConn ) {
1075 throw new DBUnexpectedError(
1076 $this,
1077 'DB connection was already closed or the connection dropped.'
1078 );
1079 }
1080
1081 return $this->mConn;
1082 }
1083
1084 /**
1085 * @param string $oldName
1086 * @param string $newName
1087 * @param bool $temporary
1088 * @param string $fname
1089 * @return bool
1090 */
1091 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1092 $tmp = $temporary ? 'TEMPORARY ' : '';
1093 $newName = $this->addIdentifierQuotes( $newName );
1094 $oldName = $this->addIdentifierQuotes( $oldName );
1095 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1096
1097 return $this->query( $query, $fname );
1098 }
1099
1100 /**
1101 * List all tables on the database
1102 *
1103 * @param string $prefix Only show tables with this prefix, e.g. mw_
1104 * @param string $fname Calling function name
1105 * @return array
1106 */
1107 function listTables( $prefix = null, $fname = __METHOD__ ) {
1108 $result = $this->query( "SHOW TABLES", $fname );
1109
1110 $endArray = array();
1111
1112 foreach ( $result as $table ) {
1113 $vars = get_object_vars( $table );
1114 $table = array_pop( $vars );
1115
1116 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1117 $endArray[] = $table;
1118 }
1119 }
1120
1121 return $endArray;
1122 }
1123
1124 /**
1125 * @param string $tableName
1126 * @param string $fName
1127 * @return bool|ResultWrapper
1128 */
1129 public function dropTable( $tableName, $fName = __METHOD__ ) {
1130 if ( !$this->tableExists( $tableName, $fName ) ) {
1131 return false;
1132 }
1133
1134 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1135 }
1136
1137 /**
1138 * @return array
1139 */
1140 protected function getDefaultSchemaVars() {
1141 $vars = parent::getDefaultSchemaVars();
1142 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1143 $vars['wgDBTableOptions'] = str_replace(
1144 'CHARSET=mysql4',
1145 'CHARSET=binary',
1146 $vars['wgDBTableOptions']
1147 );
1148
1149 return $vars;
1150 }
1151
1152 /**
1153 * Get status information from SHOW STATUS in an associative array
1154 *
1155 * @param string $which
1156 * @return array
1157 */
1158 function getMysqlStatus( $which = "%" ) {
1159 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1160 $status = array();
1161
1162 foreach ( $res as $row ) {
1163 $status[$row->Variable_name] = $row->Value;
1164 }
1165
1166 return $status;
1167 }
1168
1169 /**
1170 * Lists VIEWs in the database
1171 *
1172 * @param string $prefix Only show VIEWs with this prefix, eg.
1173 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1174 * @param string $fname Name of calling function
1175 * @return array
1176 * @since 1.22
1177 */
1178 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1179
1180 if ( !isset( $this->allViews ) ) {
1181
1182 // The name of the column containing the name of the VIEW
1183 $propertyName = 'Tables_in_' . $this->mDBname;
1184
1185 // Query for the VIEWS
1186 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1187 $this->allViews = array();
1188 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1189 array_push( $this->allViews, $row[$propertyName] );
1190 }
1191 }
1192
1193 if ( is_null( $prefix ) || $prefix === '' ) {
1194 return $this->allViews;
1195 }
1196
1197 $filteredViews = array();
1198 foreach ( $this->allViews as $viewName ) {
1199 // Does the name of this VIEW start with the table-prefix?
1200 if ( strpos( $viewName, $prefix ) === 0 ) {
1201 array_push( $filteredViews, $viewName );
1202 }
1203 }
1204
1205 return $filteredViews;
1206 }
1207
1208 /**
1209 * Differentiates between a TABLE and a VIEW.
1210 *
1211 * @param string $name Name of the TABLE/VIEW to test
1212 * @param string $prefix
1213 * @return bool
1214 * @since 1.22
1215 */
1216 public function isView( $name, $prefix = null ) {
1217 return in_array( $name, $this->listViews( $prefix ) );
1218 }
1219 }
1220
1221 /**
1222 * Utility class.
1223 * @ingroup Database
1224 */
1225 class MySQLField implements Field {
1226 private $name, $tablename, $default, $max_length, $nullable,
1227 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1228 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1229
1230 function __construct( $info ) {
1231 $this->name = $info->name;
1232 $this->tablename = $info->table;
1233 $this->default = $info->def;
1234 $this->max_length = $info->max_length;
1235 $this->nullable = !$info->not_null;
1236 $this->is_pk = $info->primary_key;
1237 $this->is_unique = $info->unique_key;
1238 $this->is_multiple = $info->multiple_key;
1239 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1240 $this->type = $info->type;
1241 $this->binary = isset( $info->binary ) ? $info->binary : false;
1242 $this->is_numeric = isset( $info->numeric ) ? $info->numeric : false;
1243 $this->is_blob = isset( $info->blob ) ? $info->blob : false;
1244 $this->is_unsigned = isset( $info->unsigned ) ? $info->unsigned : false;
1245 $this->is_zerofill = isset( $info->zerofill ) ? $info->zerofill : false;
1246 }
1247
1248 /**
1249 * @return string
1250 */
1251 function name() {
1252 return $this->name;
1253 }
1254
1255 /**
1256 * @return string
1257 */
1258 function tableName() {
1259 return $this->tablename;
1260 }
1261
1262 /**
1263 * @return string
1264 */
1265 function type() {
1266 return $this->type;
1267 }
1268
1269 /**
1270 * @return bool
1271 */
1272 function isNullable() {
1273 return $this->nullable;
1274 }
1275
1276 function defaultValue() {
1277 return $this->default;
1278 }
1279
1280 /**
1281 * @return bool
1282 */
1283 function isKey() {
1284 return $this->is_key;
1285 }
1286
1287 /**
1288 * @return bool
1289 */
1290 function isMultipleKey() {
1291 return $this->is_multiple;
1292 }
1293
1294 /**
1295 * @return bool
1296 */
1297 function isBinary() {
1298 return $this->binary;
1299 }
1300
1301 /**
1302 * @return bool
1303 */
1304 function isNumeric() {
1305 return $this->is_numeric;
1306 }
1307
1308 /**
1309 * @return bool
1310 */
1311 function isBlob() {
1312 return $this->is_blob;
1313 }
1314
1315 /**
1316 * @return bool
1317 */
1318 function isUnsigned() {
1319 return $this->is_unsigned;
1320 }
1321
1322 /**
1323 * @return bool
1324 */
1325 function isZerofill() {
1326 return $this->is_zerofill;
1327 }
1328 }
1329
1330 class MySQLMasterPos implements DBMasterPos {
1331 /** @var string */
1332 public $file;
1333 /** @var int Position */
1334 public $pos;
1335 /** @var float UNIX timestamp */
1336 public $asOfTime = 0.0;
1337
1338 function __construct( $file, $pos ) {
1339 $this->file = $file;
1340 $this->pos = $pos;
1341 $this->asOfTime = microtime( true );
1342 }
1343
1344 function __toString() {
1345 // e.g db1034-bin.000976/843431247
1346 return "{$this->file}/{$this->pos}";
1347 }
1348
1349 /**
1350 * @return array|bool (int, int)
1351 */
1352 protected function getCoordinates() {
1353 $m = array();
1354 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1355 return array( (int)$m[1], (int)$m[2] );
1356 }
1357
1358 return false;
1359 }
1360
1361 function hasReached( MySQLMasterPos $pos ) {
1362 $thisPos = $this->getCoordinates();
1363 $thatPos = $pos->getCoordinates();
1364
1365 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1366 }
1367
1368 function asOfTime() {
1369 return $this->asOfTime;
1370 }
1371 }