Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / db / DatabaseMysqlBase.php
blobc1f2969d73fbedc2ac26aeaaedc4550c450149ed
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
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.
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.
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
20 * @file
21 * @ingroup Database
24 /**
25 * Database abstraction object for MySQL.
26 * Defines methods independent on used MySQL extension.
28 * @ingroup Database
29 * @since 1.22
30 * @see Database
32 abstract class DatabaseMysqlBase extends DatabaseBase {
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
36 /** @var null|int */
37 protected $mFakeSlaveLag = null;
39 protected $mFakeMaster = false;
41 /** @var string|null */
42 private $serverVersion = null;
44 /**
45 * @return string
47 function getType() {
48 return 'mysql';
51 /**
52 * @param string $server
53 * @param string $user
54 * @param string $password
55 * @param string $dbName
56 * @throws Exception|DBConnectionError
57 * @return bool
59 function open( $server, $user, $password, $dbName ) {
60 global $wgAllDBsAreLocalhost, $wgSQLMode;
62 # Debugging hack -- fake cluster
63 if ( $wgAllDBsAreLocalhost ) {
64 $realServer = 'localhost';
65 } else {
66 $realServer = $server;
68 $this->close();
69 $this->mServer = $server;
70 $this->mUser = $user;
71 $this->mPassword = $password;
72 $this->mDBname = $dbName;
74 # The kernel's default SYN retransmission period is far too slow for us,
75 # so we use a short timeout plus a manual retry. Retrying means that a small
76 # but finite rate of SYN packet loss won't cause user-visible errors.
77 $this->mConn = false;
78 $this->installErrorHandler();
79 try {
80 $this->mConn = $this->mysqlConnect( $realServer );
81 } catch ( Exception $ex ) {
82 $this->restoreErrorHandler();
83 throw $ex;
85 $error = $this->restoreErrorHandler();
87 # Always log connection errors
88 if ( !$this->mConn ) {
89 if ( !$error ) {
90 $error = $this->lastError();
92 wfLogDBError(
93 "Error connecting to {db_server}: {error}",
94 $this->getLogContext( array(
95 'method' => __METHOD__,
96 'error' => $error,
97 ) )
99 wfDebug( "DB connection error\n" .
100 "Server: $server, User: $user, Password: " .
101 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
103 $this->reportConnectionError( $error );
106 if ( $dbName != '' ) {
107 wfSuppressWarnings();
108 $success = $this->selectDB( $dbName );
109 wfRestoreWarnings();
110 if ( !$success ) {
111 wfLogDBError(
112 "Error selecting database {db_name} on server {db_server}",
113 $this->getLogContext( array(
114 'method' => __METHOD__,
117 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
118 "from client host " . wfHostname() . "\n" );
120 $this->reportConnectionError( "Error selecting database $dbName" );
124 // Tell the server what we're communicating with
125 if ( !$this->connectInitCharset() ) {
126 $this->reportConnectionError( "Error setting character set" );
129 // Abstract over any insane MySQL defaults
130 $set = array( 'group_concat_max_len = 262144' );
131 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
132 if ( is_string( $wgSQLMode ) ) {
133 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
136 if ( $set ) {
137 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
138 $success = $this->doQuery( 'SET ' . implode( ', ', $set ), __METHOD__ );
139 if ( !$success ) {
140 wfLogDBError(
141 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
142 $this->getLogContext( array(
143 'method' => __METHOD__,
146 $this->reportConnectionError(
147 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
151 $this->mOpened = true;
153 return true;
157 * Set the character set information right after connection
158 * @return bool
160 protected function connectInitCharset() {
161 global $wgDBmysql5;
163 if ( $wgDBmysql5 ) {
164 // Tell the server we're communicating with it in UTF-8.
165 // This may engage various charset conversions.
166 return $this->mysqlSetCharset( 'utf8' );
167 } else {
168 return $this->mysqlSetCharset( 'binary' );
173 * Open a connection to a MySQL server
175 * @param string $realServer
176 * @return mixed Raw connection
177 * @throws DBConnectionError
179 abstract protected function mysqlConnect( $realServer );
182 * Set the character set of the MySQL link
184 * @param string $charset
185 * @return bool
187 abstract protected function mysqlSetCharset( $charset );
190 * @param ResultWrapper|resource $res
191 * @throws DBUnexpectedError
193 function freeResult( $res ) {
194 if ( $res instanceof ResultWrapper ) {
195 $res = $res->result;
197 wfSuppressWarnings();
198 $ok = $this->mysqlFreeResult( $res );
199 wfRestoreWarnings();
200 if ( !$ok ) {
201 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
206 * Free result memory
208 * @param resource $res Raw result
209 * @return bool
211 abstract protected function mysqlFreeResult( $res );
214 * @param ResultWrapper|resource $res
215 * @return stdClass|bool
216 * @throws DBUnexpectedError
218 function fetchObject( $res ) {
219 if ( $res instanceof ResultWrapper ) {
220 $res = $res->result;
222 wfSuppressWarnings();
223 $row = $this->mysqlFetchObject( $res );
224 wfRestoreWarnings();
226 $errno = $this->lastErrno();
227 // Unfortunately, mysql_fetch_object does not reset the last errno.
228 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
229 // these are the only errors mysql_fetch_object can cause.
230 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
231 if ( $errno == 2000 || $errno == 2013 ) {
232 throw new DBUnexpectedError(
233 $this,
234 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
238 return $row;
242 * Fetch a result row as an object
244 * @param resource $res Raw result
245 * @return stdClass
247 abstract protected function mysqlFetchObject( $res );
250 * @param ResultWrapper|resource $res
251 * @return array|bool
252 * @throws DBUnexpectedError
254 function fetchRow( $res ) {
255 if ( $res instanceof ResultWrapper ) {
256 $res = $res->result;
258 wfSuppressWarnings();
259 $row = $this->mysqlFetchArray( $res );
260 wfRestoreWarnings();
262 $errno = $this->lastErrno();
263 // Unfortunately, mysql_fetch_array does not reset the last errno.
264 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
265 // these are the only errors mysql_fetch_array can cause.
266 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
267 if ( $errno == 2000 || $errno == 2013 ) {
268 throw new DBUnexpectedError(
269 $this,
270 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
274 return $row;
278 * Fetch a result row as an associative and numeric array
280 * @param resource $res Raw result
281 * @return array
283 abstract protected function mysqlFetchArray( $res );
286 * @throws DBUnexpectedError
287 * @param ResultWrapper|resource $res
288 * @return int
290 function numRows( $res ) {
291 if ( $res instanceof ResultWrapper ) {
292 $res = $res->result;
294 wfSuppressWarnings();
295 $n = $this->mysqlNumRows( $res );
296 wfRestoreWarnings();
298 // Unfortunately, mysql_num_rows does not reset the last errno.
299 // We are not checking for any errors here, since
300 // these are no errors mysql_num_rows can cause.
301 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
302 // See https://bugzilla.wikimedia.org/42430
303 return $n;
307 * Get number of rows in result
309 * @param resource $res Raw result
310 * @return int
312 abstract protected function mysqlNumRows( $res );
315 * @param ResultWrapper|resource $res
316 * @return int
318 function numFields( $res ) {
319 if ( $res instanceof ResultWrapper ) {
320 $res = $res->result;
323 return $this->mysqlNumFields( $res );
327 * Get number of fields in result
329 * @param resource $res Raw result
330 * @return int
332 abstract protected function mysqlNumFields( $res );
335 * @param ResultWrapper|resource $res
336 * @param int $n
337 * @return string
339 function fieldName( $res, $n ) {
340 if ( $res instanceof ResultWrapper ) {
341 $res = $res->result;
344 return $this->mysqlFieldName( $res, $n );
348 * Get the name of the specified field in a result
350 * @param ResultWrapper|resource $res
351 * @param int $n
352 * @return string
354 abstract protected function mysqlFieldName( $res, $n );
357 * mysql_field_type() wrapper
358 * @param ResultWrapper|resource $res
359 * @param int $n
360 * @return string
362 public function fieldType( $res, $n ) {
363 if ( $res instanceof ResultWrapper ) {
364 $res = $res->result;
367 return $this->mysqlFieldType( $res, $n );
371 * Get the type of the specified field in a result
373 * @param ResultWrapper|resource $res
374 * @param int $n
375 * @return string
377 abstract protected function mysqlFieldType( $res, $n );
380 * @param ResultWrapper|resource $res
381 * @param int $row
382 * @return bool
384 function dataSeek( $res, $row ) {
385 if ( $res instanceof ResultWrapper ) {
386 $res = $res->result;
389 return $this->mysqlDataSeek( $res, $row );
393 * Move internal result pointer
395 * @param ResultWrapper|resource $res
396 * @param int $row
397 * @return bool
399 abstract protected function mysqlDataSeek( $res, $row );
402 * @return string
404 function lastError() {
405 if ( $this->mConn ) {
406 # Even if it's non-zero, it can still be invalid
407 wfSuppressWarnings();
408 $error = $this->mysqlError( $this->mConn );
409 if ( !$error ) {
410 $error = $this->mysqlError();
412 wfRestoreWarnings();
413 } else {
414 $error = $this->mysqlError();
416 if ( $error ) {
417 $error .= ' (' . $this->mServer . ')';
420 return $error;
424 * Returns the text of the error message from previous MySQL operation
426 * @param resource $conn Raw connection
427 * @return string
429 abstract protected function mysqlError( $conn = null );
432 * @param string $table
433 * @param array $uniqueIndexes
434 * @param array $rows
435 * @param string $fname
436 * @return ResultWrapper
438 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
439 return $this->nativeReplace( $table, $rows, $fname );
443 * Estimate rows in dataset
444 * Returns estimated count, based on EXPLAIN output
445 * Takes same arguments as Database::select()
447 * @param string|array $table
448 * @param string|array $vars
449 * @param string|array $conds
450 * @param string $fname
451 * @param string|array $options
452 * @return bool|int
454 public function estimateRowCount( $table, $vars = '*', $conds = '',
455 $fname = __METHOD__, $options = array()
457 $options['EXPLAIN'] = true;
458 $res = $this->select( $table, $vars, $conds, $fname, $options );
459 if ( $res === false ) {
460 return false;
462 if ( !$this->numRows( $res ) ) {
463 return 0;
466 $rows = 1;
467 foreach ( $res as $plan ) {
468 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
471 return (int)$rows;
475 * @param string $table
476 * @param string $field
477 * @return bool|MySQLField
479 function fieldInfo( $table, $field ) {
480 $table = $this->tableName( $table );
481 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
482 if ( !$res ) {
483 return false;
485 $n = $this->mysqlNumFields( $res->result );
486 for ( $i = 0; $i < $n; $i++ ) {
487 $meta = $this->mysqlFetchField( $res->result, $i );
488 if ( $field == $meta->name ) {
489 return new MySQLField( $meta );
493 return false;
497 * Get column information from a result
499 * @param resource $res Raw result
500 * @param int $n
501 * @return stdClass
503 abstract protected function mysqlFetchField( $res, $n );
506 * Get information about an index into an object
507 * Returns false if the index does not exist
509 * @param string $table
510 * @param string $index
511 * @param string $fname
512 * @return bool|array|null False or null on failure
514 function indexInfo( $table, $index, $fname = __METHOD__ ) {
515 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
516 # SHOW INDEX should work for 3.x and up:
517 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
518 $table = $this->tableName( $table );
519 $index = $this->indexName( $index );
521 $sql = 'SHOW INDEX FROM ' . $table;
522 $res = $this->query( $sql, $fname );
524 if ( !$res ) {
525 return null;
528 $result = array();
530 foreach ( $res as $row ) {
531 if ( $row->Key_name == $index ) {
532 $result[] = $row;
536 return empty( $result ) ? false : $result;
540 * @param string $s
541 * @return string
543 function strencode( $s ) {
544 $sQuoted = $this->mysqlRealEscapeString( $s );
546 if ( $sQuoted === false ) {
547 $this->ping();
548 $sQuoted = $this->mysqlRealEscapeString( $s );
551 return $sQuoted;
555 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
557 * @param string $s
558 * @return string
560 public function addIdentifierQuotes( $s ) {
561 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
562 // Remove NUL bytes and escape backticks by doubling
563 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
567 * @param string $name
568 * @return bool
570 public function isQuotedIdentifier( $name ) {
571 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
575 * @return bool
577 function ping() {
578 $ping = $this->mysqlPing();
579 if ( $ping ) {
580 return true;
583 $this->closeConnection();
584 $this->mOpened = false;
585 $this->mConn = false;
586 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
588 return true;
592 * Ping a server connection or reconnect if there is no connection
594 * @return bool
596 abstract protected function mysqlPing();
599 * Set lag time in seconds for a fake slave
601 * @param int $lag
603 public function setFakeSlaveLag( $lag ) {
604 $this->mFakeSlaveLag = $lag;
608 * Make this connection a fake master
610 * @param bool $enabled
612 public function setFakeMaster( $enabled = true ) {
613 $this->mFakeMaster = $enabled;
617 * Returns slave lag.
619 * This will do a SHOW SLAVE STATUS
621 * @return int
623 function getLag() {
624 if ( !is_null( $this->mFakeSlaveLag ) ) {
625 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
627 return $this->mFakeSlaveLag;
630 return $this->getLagFromSlaveStatus();
634 * @return bool|int
636 function getLagFromSlaveStatus() {
637 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
638 if ( !$res ) {
639 return false;
641 $row = $res->fetchObject();
642 if ( !$row ) {
643 return false;
645 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
646 return false;
647 } else {
648 return intval( $row->Seconds_Behind_Master );
653 * Wait for the slave to catch up to a given master position.
654 * @todo Return values for this and base class are rubbish
656 * @param DBMasterPos|MySQLMasterPos $pos
657 * @param int $timeout The maximum number of seconds to wait for synchronisation
658 * @return int Zero if the slave was past that position already,
659 * greater than zero if we waited for some period of time, less than
660 * zero if we timed out.
662 function masterPosWait( DBMasterPos $pos, $timeout ) {
663 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
664 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
667 # Commit any open transactions
668 $this->commit( __METHOD__, 'flush' );
670 if ( !is_null( $this->mFakeSlaveLag ) ) {
671 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
673 if ( $wait > $timeout * 1e6 ) {
674 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
676 return -1;
677 } elseif ( $wait > 0 ) {
678 wfDebug( "Fake slave waiting $wait us\n" );
679 usleep( $wait );
681 return 1;
682 } else {
683 wfDebug( "Fake slave up to date ($wait us)\n" );
685 return 0;
689 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
690 $encFile = $this->addQuotes( $pos->file );
691 $encPos = intval( $pos->pos );
692 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
693 $res = $this->doQuery( $sql );
695 $status = false;
696 if ( $res && $row = $this->fetchRow( $res ) ) {
697 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
698 if ( ctype_digit( $status ) ) { // success
699 $this->lastKnownSlavePos = $pos;
703 return $status;
707 * Get the position of the master from SHOW SLAVE STATUS
709 * @return MySQLMasterPos|bool
711 function getSlavePos() {
712 if ( !is_null( $this->mFakeSlaveLag ) ) {
713 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
714 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
716 return $pos;
719 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
720 $row = $this->fetchObject( $res );
722 if ( $row ) {
723 $pos = isset( $row->Exec_master_log_pos )
724 ? $row->Exec_master_log_pos
725 : $row->Exec_Master_Log_Pos;
727 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
728 } else {
729 return false;
734 * Get the position of the master from SHOW MASTER STATUS
736 * @return MySQLMasterPos|bool
738 function getMasterPos() {
739 if ( $this->mFakeMaster ) {
740 return new MySQLMasterPos( 'fake', microtime( true ) );
743 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
744 $row = $this->fetchObject( $res );
746 if ( $row ) {
747 return new MySQLMasterPos( $row->File, $row->Position );
748 } else {
749 return false;
754 * @param string $index
755 * @return string
757 function useIndexClause( $index ) {
758 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
762 * @return string
764 function lowPriorityOption() {
765 return 'LOW_PRIORITY';
769 * @return string
771 public function getSoftwareLink() {
772 // MariaDB includes its name in its version string; this is how MariaDB's version of
773 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
774 // in libmysql/libmysql.c).
775 $version = $this->getServerVersion();
776 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
777 return '[{{int:version-db-mariadb-url}} MariaDB]';
780 // Percona Server's version suffix is not very distinctive, and @@version_comment
781 // doesn't give the necessary info for source builds, so assume the server is MySQL.
782 // (Even Percona's version of mysql doesn't try to make the distinction.)
783 return '[{{int:version-db-mysql-url}} MySQL]';
787 * @return string
789 public function getServerVersion() {
790 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
791 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
792 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
793 if ( $this->serverVersion === null ) {
794 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
796 return $this->serverVersion;
800 * @param array $options
802 public function setSessionOptions( array $options ) {
803 if ( isset( $options['connTimeout'] ) ) {
804 $timeout = (int)$options['connTimeout'];
805 $this->query( "SET net_read_timeout=$timeout" );
806 $this->query( "SET net_write_timeout=$timeout" );
811 * @param string $sql
812 * @param string $newLine
813 * @return bool
815 public function streamStatementEnd( &$sql, &$newLine ) {
816 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
817 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
818 $this->delimiter = $m[1];
819 $newLine = '';
822 return parent::streamStatementEnd( $sql, $newLine );
826 * Check to see if a named lock is available. This is non-blocking.
828 * @param string $lockName Name of lock to poll
829 * @param string $method Name of method calling us
830 * @return bool
831 * @since 1.20
833 public function lockIsFree( $lockName, $method ) {
834 $lockName = $this->addQuotes( $lockName );
835 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
836 $row = $this->fetchObject( $result );
838 return ( $row->lockstatus == 1 );
842 * @param string $lockName
843 * @param string $method
844 * @param int $timeout
845 * @return bool
847 public function lock( $lockName, $method, $timeout = 5 ) {
848 $lockName = $this->addQuotes( $lockName );
849 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
850 $row = $this->fetchObject( $result );
852 if ( $row->lockstatus == 1 ) {
853 return true;
854 } else {
855 wfDebug( __METHOD__ . " failed to acquire lock\n" );
857 return false;
862 * FROM MYSQL DOCS:
863 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
864 * @param string $lockName
865 * @param string $method
866 * @return bool
868 public function unlock( $lockName, $method ) {
869 $lockName = $this->addQuotes( $lockName );
870 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
871 $row = $this->fetchObject( $result );
873 return ( $row->lockstatus == 1 );
877 * @param array $read
878 * @param array $write
879 * @param string $method
880 * @param bool $lowPriority
881 * @return bool
883 public function lockTables( $read, $write, $method, $lowPriority = true ) {
884 $items = array();
886 foreach ( $write as $table ) {
887 $tbl = $this->tableName( $table ) .
888 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
889 ' WRITE';
890 $items[] = $tbl;
892 foreach ( $read as $table ) {
893 $items[] = $this->tableName( $table ) . ' READ';
895 $sql = "LOCK TABLES " . implode( ',', $items );
896 $this->query( $sql, $method );
898 return true;
902 * @param string $method
903 * @return bool
905 public function unlockTables( $method ) {
906 $this->query( "UNLOCK TABLES", $method );
908 return true;
912 * Get search engine class. All subclasses of this
913 * need to implement this if they wish to use searching.
915 * @return string
917 public function getSearchEngine() {
918 return 'SearchMySQL';
922 * @param bool $value
924 public function setBigSelects( $value = true ) {
925 if ( $value === 'default' ) {
926 if ( $this->mDefaultBigSelects === null ) {
927 # Function hasn't been called before so it must already be set to the default
928 return;
929 } else {
930 $value = $this->mDefaultBigSelects;
932 } elseif ( $this->mDefaultBigSelects === null ) {
933 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
935 $encValue = $value ? '1' : '0';
936 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
940 * DELETE where the condition is a join. MySql uses multi-table deletes.
941 * @param string $delTable
942 * @param string $joinTable
943 * @param string $delVar
944 * @param string $joinVar
945 * @param array|string $conds
946 * @param bool|string $fname
947 * @throws DBUnexpectedError
948 * @return bool|ResultWrapper
950 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
951 if ( !$conds ) {
952 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
955 $delTable = $this->tableName( $delTable );
956 $joinTable = $this->tableName( $joinTable );
957 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
959 if ( $conds != '*' ) {
960 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
963 return $this->query( $sql, $fname );
967 * @param string $table
968 * @param array $rows
969 * @param array $uniqueIndexes
970 * @param array $set
971 * @param string $fname
972 * @return bool
974 public function upsert( $table, array $rows, array $uniqueIndexes,
975 array $set, $fname = __METHOD__
977 if ( !count( $rows ) ) {
978 return true; // nothing to do
981 if ( !is_array( reset( $rows ) ) ) {
982 $rows = array( $rows );
985 $table = $this->tableName( $table );
986 $columns = array_keys( $rows[0] );
988 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
989 $rowTuples = array();
990 foreach ( $rows as $row ) {
991 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
993 $sql .= implode( ',', $rowTuples );
994 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
996 return (bool)$this->query( $sql, $fname );
1000 * Determines how long the server has been up
1002 * @return int
1004 function getServerUptime() {
1005 $vars = $this->getMysqlStatus( 'Uptime' );
1007 return (int)$vars['Uptime'];
1011 * Determines if the last failure was due to a deadlock
1013 * @return bool
1015 function wasDeadlock() {
1016 return $this->lastErrno() == 1213;
1020 * Determines if the last failure was due to a lock timeout
1022 * @return bool
1024 function wasLockTimeout() {
1025 return $this->lastErrno() == 1205;
1029 * Determines if the last query error was something that should be dealt
1030 * with by pinging the connection and reissuing the query
1032 * @return bool
1034 function wasErrorReissuable() {
1035 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1039 * Determines if the last failure was due to the database being read-only.
1041 * @return bool
1043 function wasReadOnlyError() {
1044 return $this->lastErrno() == 1223 ||
1045 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1049 * @param string $oldName
1050 * @param string $newName
1051 * @param bool $temporary
1052 * @param string $fname
1053 * @return bool
1055 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1056 $tmp = $temporary ? 'TEMPORARY ' : '';
1057 $newName = $this->addIdentifierQuotes( $newName );
1058 $oldName = $this->addIdentifierQuotes( $oldName );
1059 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1061 return $this->query( $query, $fname );
1065 * List all tables on the database
1067 * @param string $prefix Only show tables with this prefix, e.g. mw_
1068 * @param string $fname Calling function name
1069 * @return array
1071 function listTables( $prefix = null, $fname = __METHOD__ ) {
1072 $result = $this->query( "SHOW TABLES", $fname );
1074 $endArray = array();
1076 foreach ( $result as $table ) {
1077 $vars = get_object_vars( $table );
1078 $table = array_pop( $vars );
1080 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1081 $endArray[] = $table;
1085 return $endArray;
1089 * @param string $tableName
1090 * @param string $fName
1091 * @return bool|ResultWrapper
1093 public function dropTable( $tableName, $fName = __METHOD__ ) {
1094 if ( !$this->tableExists( $tableName, $fName ) ) {
1095 return false;
1098 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1102 * @return array
1104 protected function getDefaultSchemaVars() {
1105 $vars = parent::getDefaultSchemaVars();
1106 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1107 $vars['wgDBTableOptions'] = str_replace(
1108 'CHARSET=mysql4',
1109 'CHARSET=binary',
1110 $vars['wgDBTableOptions']
1113 return $vars;
1117 * Get status information from SHOW STATUS in an associative array
1119 * @param string $which
1120 * @return array
1122 function getMysqlStatus( $which = "%" ) {
1123 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1124 $status = array();
1126 foreach ( $res as $row ) {
1127 $status[$row->Variable_name] = $row->Value;
1130 return $status;
1134 * Lists VIEWs in the database
1136 * @param string $prefix Only show VIEWs with this prefix, eg.
1137 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1138 * @param string $fname Name of calling function
1139 * @return array
1140 * @since 1.22
1142 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1144 if ( !isset( $this->allViews ) ) {
1146 // The name of the column containing the name of the VIEW
1147 $propertyName = 'Tables_in_' . $this->mDBname;
1149 // Query for the VIEWS
1150 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1151 $this->allViews = array();
1152 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1153 array_push( $this->allViews, $row[$propertyName] );
1157 if ( is_null( $prefix ) || $prefix === '' ) {
1158 return $this->allViews;
1161 $filteredViews = array();
1162 foreach ( $this->allViews as $viewName ) {
1163 // Does the name of this VIEW start with the table-prefix?
1164 if ( strpos( $viewName, $prefix ) === 0 ) {
1165 array_push( $filteredViews, $viewName );
1169 return $filteredViews;
1173 * Differentiates between a TABLE and a VIEW.
1175 * @param string $name Name of the TABLE/VIEW to test
1176 * @param string $prefix
1177 * @return bool
1178 * @since 1.22
1180 public function isView( $name, $prefix = null ) {
1181 return in_array( $name, $this->listViews( $prefix ) );
1186 * Utility class.
1187 * @ingroup Database
1189 class MySQLField implements Field {
1190 private $name, $tablename, $default, $max_length, $nullable,
1191 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1193 function __construct( $info ) {
1194 $this->name = $info->name;
1195 $this->tablename = $info->table;
1196 $this->default = $info->def;
1197 $this->max_length = $info->max_length;
1198 $this->nullable = !$info->not_null;
1199 $this->is_pk = $info->primary_key;
1200 $this->is_unique = $info->unique_key;
1201 $this->is_multiple = $info->multiple_key;
1202 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1203 $this->type = $info->type;
1204 $this->flags = $info->flags;
1205 $this->binary = isset( $info->binary ) ? $info->binary : false;
1209 * @return string
1211 function name() {
1212 return $this->name;
1216 * @return string
1218 function tableName() {
1219 return $this->tableName;
1223 * @return string
1225 function type() {
1226 return $this->type;
1230 * @return bool
1232 function isNullable() {
1233 return $this->nullable;
1236 function defaultValue() {
1237 return $this->default;
1241 * @return bool
1243 function isKey() {
1244 return $this->is_key;
1248 * @return bool
1250 function isMultipleKey() {
1251 return $this->is_multiple;
1255 * @return int
1257 function flags() {
1258 return $this->flags;
1261 function isBinary() {
1262 return $this->binary;
1266 class MySQLMasterPos implements DBMasterPos {
1267 /** @var string */
1268 public $file;
1269 /** @var int Position */
1270 public $pos;
1271 /** @var float UNIX timestamp */
1272 public $asOfTime = 0.0;
1274 function __construct( $file, $pos ) {
1275 $this->file = $file;
1276 $this->pos = $pos;
1277 $this->asOfTime = microtime( true );
1280 function __toString() {
1281 // e.g db1034-bin.000976/843431247
1282 return "{$this->file}/{$this->pos}";
1286 * @return array|bool (int, int)
1288 protected function getCoordinates() {
1289 $m = array();
1290 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1291 return array( (int)$m[1], (int)$m[2] );
1294 return false;
1297 function hasReached( MySQLMasterPos $pos ) {
1298 $thisPos = $this->getCoordinates();
1299 $thatPos = $pos->getCoordinates();
1301 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1304 function asOfTime() {
1305 return $this->asOfTime;