Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / db / DatabaseMysqlBase.php
blobcf377361ada168c55d7bec80934cf9cac74ffe9e
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 /**
42 * @return string
44 function getType() {
45 return 'mysql';
48 /**
49 * @param string $server
50 * @param string $user
51 * @param string $password
52 * @param string $dbName
53 * @throws Exception|DBConnectionError
54 * @return bool
56 function open( $server, $user, $password, $dbName ) {
57 global $wgAllDBsAreLocalhost, $wgSQLMode;
58 wfProfileIn( __METHOD__ );
60 # Debugging hack -- fake cluster
61 if ( $wgAllDBsAreLocalhost ) {
62 $realServer = 'localhost';
63 } else {
64 $realServer = $server;
66 $this->close();
67 $this->mServer = $server;
68 $this->mUser = $user;
69 $this->mPassword = $password;
70 $this->mDBname = $dbName;
72 wfProfileIn( "dbconnect-$server" );
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 wfProfileOut( "dbconnect-$server" );
83 wfProfileOut( __METHOD__ );
84 $this->restoreErrorHandler();
85 throw $ex;
87 $error = $this->restoreErrorHandler();
89 wfProfileOut( "dbconnect-$server" );
91 # Always log connection errors
92 if ( !$this->mConn ) {
93 if ( !$error ) {
94 $error = $this->lastError();
96 wfLogDBError( "Error connecting to {$this->mServer}: $error" );
97 wfDebug( "DB connection error\n" .
98 "Server: $server, User: $user, Password: " .
99 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
101 wfProfileOut( __METHOD__ );
103 $this->reportConnectionError( $error );
106 if ( $dbName != '' ) {
107 wfSuppressWarnings();
108 $success = $this->selectDB( $dbName );
109 wfRestoreWarnings();
110 if ( !$success ) {
111 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}" );
112 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
113 "from client host " . wfHostname() . "\n" );
115 wfProfileOut( __METHOD__ );
117 $this->reportConnectionError( "Error selecting database $dbName" );
121 // Tell the server what we're communicating with
122 if ( !$this->connectInitCharset() ) {
123 $this->reportConnectionError( "Error setting character set" );
126 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
127 if ( is_string( $wgSQLMode ) ) {
128 $mode = $this->addQuotes( $wgSQLMode );
129 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
130 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__ );
131 if ( !$success ) {
132 wfLogDBError( "Error setting sql_mode to $mode on server {$this->mServer}" );
133 wfProfileOut( __METHOD__ );
134 $this->reportConnectionError( "Error setting sql_mode to $mode" );
138 $this->mOpened = true;
139 wfProfileOut( __METHOD__ );
141 return true;
145 * Set the character set information right after connection
146 * @return bool
148 protected function connectInitCharset() {
149 global $wgDBmysql5;
151 if ( $wgDBmysql5 ) {
152 // Tell the server we're communicating with it in UTF-8.
153 // This may engage various charset conversions.
154 return $this->mysqlSetCharset( 'utf8' );
155 } else {
156 return $this->mysqlSetCharset( 'binary' );
161 * Open a connection to a MySQL server
163 * @param string $realServer
164 * @return mixed Raw connection
165 * @throws DBConnectionError
167 abstract protected function mysqlConnect( $realServer );
170 * Set the character set of the MySQL link
172 * @param string $charset
173 * @return bool
175 abstract protected function mysqlSetCharset( $charset );
178 * @param ResultWrapper|resource $res
179 * @throws DBUnexpectedError
181 function freeResult( $res ) {
182 if ( $res instanceof ResultWrapper ) {
183 $res = $res->result;
185 wfSuppressWarnings();
186 $ok = $this->mysqlFreeResult( $res );
187 wfRestoreWarnings();
188 if ( !$ok ) {
189 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
194 * Free result memory
196 * @param resource $res Raw result
197 * @return bool
199 abstract protected function mysqlFreeResult( $res );
202 * @param ResultWrapper|resource $res
203 * @return stdClass|bool
204 * @throws DBUnexpectedError
206 function fetchObject( $res ) {
207 if ( $res instanceof ResultWrapper ) {
208 $res = $res->result;
210 wfSuppressWarnings();
211 $row = $this->mysqlFetchObject( $res );
212 wfRestoreWarnings();
214 $errno = $this->lastErrno();
215 // Unfortunately, mysql_fetch_object does not reset the last errno.
216 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
217 // these are the only errors mysql_fetch_object can cause.
218 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
219 if ( $errno == 2000 || $errno == 2013 ) {
220 throw new DBUnexpectedError(
221 $this,
222 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
226 return $row;
230 * Fetch a result row as an object
232 * @param resource $res Raw result
233 * @return stdClass
235 abstract protected function mysqlFetchObject( $res );
238 * @param ResultWrapper|resource $res
239 * @return array|bool
240 * @throws DBUnexpectedError
242 function fetchRow( $res ) {
243 if ( $res instanceof ResultWrapper ) {
244 $res = $res->result;
246 wfSuppressWarnings();
247 $row = $this->mysqlFetchArray( $res );
248 wfRestoreWarnings();
250 $errno = $this->lastErrno();
251 // Unfortunately, mysql_fetch_array does not reset the last errno.
252 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
253 // these are the only errors mysql_fetch_array can cause.
254 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
255 if ( $errno == 2000 || $errno == 2013 ) {
256 throw new DBUnexpectedError(
257 $this,
258 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
262 return $row;
266 * Fetch a result row as an associative and numeric array
268 * @param resource $res Raw result
269 * @return array
271 abstract protected function mysqlFetchArray( $res );
274 * @throws DBUnexpectedError
275 * @param ResultWrapper|resource $res
276 * @return int
278 function numRows( $res ) {
279 if ( $res instanceof ResultWrapper ) {
280 $res = $res->result;
282 wfSuppressWarnings();
283 $n = $this->mysqlNumRows( $res );
284 wfRestoreWarnings();
286 // Unfortunately, mysql_num_rows does not reset the last errno.
287 // We are not checking for any errors here, since
288 // these are no errors mysql_num_rows can cause.
289 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
290 // See https://bugzilla.wikimedia.org/42430
291 return $n;
295 * Get number of rows in result
297 * @param resource $res Raw result
298 * @return int
300 abstract protected function mysqlNumRows( $res );
303 * @param ResultWrapper|resource $res
304 * @return int
306 function numFields( $res ) {
307 if ( $res instanceof ResultWrapper ) {
308 $res = $res->result;
311 return $this->mysqlNumFields( $res );
315 * Get number of fields in result
317 * @param resource $res Raw result
318 * @return int
320 abstract protected function mysqlNumFields( $res );
323 * @param ResultWrapper|resource $res
324 * @param int $n
325 * @return string
327 function fieldName( $res, $n ) {
328 if ( $res instanceof ResultWrapper ) {
329 $res = $res->result;
332 return $this->mysqlFieldName( $res, $n );
336 * Get the name of the specified field in a result
338 * @param ResultWrapper|resource $res
339 * @param int $n
340 * @return string
342 abstract protected function mysqlFieldName( $res, $n );
345 * mysql_field_type() wrapper
346 * @param ResultWrapper|resource $res
347 * @param int $n
348 * @return string
350 public function fieldType( $res, $n ) {
351 if ( $res instanceof ResultWrapper ) {
352 $res = $res->result;
355 return $this->mysqlFieldType( $res, $n );
359 * Get the type of the specified field in a result
361 * @param ResultWrapper|resource $res
362 * @param int $n
363 * @return string
365 abstract protected function mysqlFieldType( $res, $n );
368 * @param ResultWrapper|resource $res
369 * @param int $row
370 * @return bool
372 function dataSeek( $res, $row ) {
373 if ( $res instanceof ResultWrapper ) {
374 $res = $res->result;
377 return $this->mysqlDataSeek( $res, $row );
381 * Move internal result pointer
383 * @param ResultWrapper|resource $res
384 * @param int $row
385 * @return bool
387 abstract protected function mysqlDataSeek( $res, $row );
390 * @return string
392 function lastError() {
393 if ( $this->mConn ) {
394 # Even if it's non-zero, it can still be invalid
395 wfSuppressWarnings();
396 $error = $this->mysqlError( $this->mConn );
397 if ( !$error ) {
398 $error = $this->mysqlError();
400 wfRestoreWarnings();
401 } else {
402 $error = $this->mysqlError();
404 if ( $error ) {
405 $error .= ' (' . $this->mServer . ')';
408 return $error;
412 * Returns the text of the error message from previous MySQL operation
414 * @param resource $conn Raw connection
415 * @return string
417 abstract protected function mysqlError( $conn = null );
420 * @param string $table
421 * @param array $uniqueIndexes
422 * @param array $rows
423 * @param string $fname
424 * @return ResultWrapper
426 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
427 return $this->nativeReplace( $table, $rows, $fname );
431 * Estimate rows in dataset
432 * Returns estimated count, based on EXPLAIN output
433 * Takes same arguments as Database::select()
435 * @param string|array $table
436 * @param string|array $vars
437 * @param string|array $conds
438 * @param string $fname
439 * @param string|array $options
440 * @return bool|int
442 public function estimateRowCount( $table, $vars = '*', $conds = '',
443 $fname = __METHOD__, $options = array()
445 $options['EXPLAIN'] = true;
446 $res = $this->select( $table, $vars, $conds, $fname, $options );
447 if ( $res === false ) {
448 return false;
450 if ( !$this->numRows( $res ) ) {
451 return 0;
454 $rows = 1;
455 foreach ( $res as $plan ) {
456 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
459 return $rows;
463 * @param string $table
464 * @param string $field
465 * @return bool|MySQLField
467 function fieldInfo( $table, $field ) {
468 $table = $this->tableName( $table );
469 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
470 if ( !$res ) {
471 return false;
473 $n = $this->mysqlNumFields( $res->result );
474 for ( $i = 0; $i < $n; $i++ ) {
475 $meta = $this->mysqlFetchField( $res->result, $i );
476 if ( $field == $meta->name ) {
477 return new MySQLField( $meta );
481 return false;
485 * Get column information from a result
487 * @param resource $res Raw result
488 * @param int $n
489 * @return stdClass
491 abstract protected function mysqlFetchField( $res, $n );
494 * Get information about an index into an object
495 * Returns false if the index does not exist
497 * @param string $table
498 * @param string $index
499 * @param string $fname
500 * @return bool|array|null False or null on failure
502 function indexInfo( $table, $index, $fname = __METHOD__ ) {
503 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
504 # SHOW INDEX should work for 3.x and up:
505 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
506 $table = $this->tableName( $table );
507 $index = $this->indexName( $index );
509 $sql = 'SHOW INDEX FROM ' . $table;
510 $res = $this->query( $sql, $fname );
512 if ( !$res ) {
513 return null;
516 $result = array();
518 foreach ( $res as $row ) {
519 if ( $row->Key_name == $index ) {
520 $result[] = $row;
524 return empty( $result ) ? false : $result;
528 * @param string $s
529 * @return string
531 function strencode( $s ) {
532 $sQuoted = $this->mysqlRealEscapeString( $s );
534 if ( $sQuoted === false ) {
535 $this->ping();
536 $sQuoted = $this->mysqlRealEscapeString( $s );
539 return $sQuoted;
543 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
545 * @param string $s
546 * @return string
548 public function addIdentifierQuotes( $s ) {
549 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
550 // Remove NUL bytes and escape backticks by doubling
551 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
555 * @param string $name
556 * @return bool
558 public function isQuotedIdentifier( $name ) {
559 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
563 * @return bool
565 function ping() {
566 $ping = $this->mysqlPing();
567 if ( $ping ) {
568 return true;
571 $this->closeConnection();
572 $this->mOpened = false;
573 $this->mConn = false;
574 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
576 return true;
580 * Ping a server connection or reconnect if there is no connection
582 * @return bool
584 abstract protected function mysqlPing();
587 * Set lag time in seconds for a fake slave
589 * @param int $lag
591 public function setFakeSlaveLag( $lag ) {
592 $this->mFakeSlaveLag = $lag;
596 * Make this connection a fake master
598 * @param bool $enabled
600 public function setFakeMaster( $enabled = true ) {
601 $this->mFakeMaster = $enabled;
605 * Returns slave lag.
607 * This will do a SHOW SLAVE STATUS
609 * @return int
611 function getLag() {
612 if ( !is_null( $this->mFakeSlaveLag ) ) {
613 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
615 return $this->mFakeSlaveLag;
618 return $this->getLagFromSlaveStatus();
622 * @return bool|int
624 function getLagFromSlaveStatus() {
625 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
626 if ( !$res ) {
627 return false;
629 $row = $res->fetchObject();
630 if ( !$row ) {
631 return false;
633 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
634 return false;
635 } else {
636 return intval( $row->Seconds_Behind_Master );
641 * Wait for the slave to catch up to a given master position.
642 * @todo Return values for this and base class are rubbish
644 * @param DBMasterPos|MySQLMasterPos $pos
645 * @param int $timeout The maximum number of seconds to wait for synchronisation
646 * @return int Zero if the slave was past that position already,
647 * greater than zero if we waited for some period of time, less than
648 * zero if we timed out.
650 function masterPosWait( DBMasterPos $pos, $timeout ) {
651 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
652 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
655 wfProfileIn( __METHOD__ );
656 # Commit any open transactions
657 $this->commit( __METHOD__, 'flush' );
659 if ( !is_null( $this->mFakeSlaveLag ) ) {
660 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
662 if ( $wait > $timeout * 1e6 ) {
663 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
664 wfProfileOut( __METHOD__ );
666 return -1;
667 } elseif ( $wait > 0 ) {
668 wfDebug( "Fake slave waiting $wait us\n" );
669 usleep( $wait );
670 wfProfileOut( __METHOD__ );
672 return 1;
673 } else {
674 wfDebug( "Fake slave up to date ($wait us)\n" );
675 wfProfileOut( __METHOD__ );
677 return 0;
681 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
682 $encFile = $this->addQuotes( $pos->file );
683 $encPos = intval( $pos->pos );
684 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
685 $res = $this->doQuery( $sql );
687 $status = false;
688 if ( $res && $row = $this->fetchRow( $res ) ) {
689 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
690 if ( ctype_digit( $status ) ) { // success
691 $this->lastKnownSlavePos = $pos;
695 wfProfileOut( __METHOD__ );
697 return $status;
701 * Get the position of the master from SHOW SLAVE STATUS
703 * @return MySQLMasterPos|bool
705 function getSlavePos() {
706 if ( !is_null( $this->mFakeSlaveLag ) ) {
707 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
708 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
710 return $pos;
713 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
714 $row = $this->fetchObject( $res );
716 if ( $row ) {
717 $pos = isset( $row->Exec_master_log_pos )
718 ? $row->Exec_master_log_pos
719 : $row->Exec_Master_Log_Pos;
721 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
722 } else {
723 return false;
728 * Get the position of the master from SHOW MASTER STATUS
730 * @return MySQLMasterPos|bool
732 function getMasterPos() {
733 if ( $this->mFakeMaster ) {
734 return new MySQLMasterPos( 'fake', microtime( true ) );
737 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
738 $row = $this->fetchObject( $res );
740 if ( $row ) {
741 return new MySQLMasterPos( $row->File, $row->Position );
742 } else {
743 return false;
748 * @param string $index
749 * @return string
751 function useIndexClause( $index ) {
752 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
756 * @return string
758 function lowPriorityOption() {
759 return 'LOW_PRIORITY';
763 * @return string
765 public function getSoftwareLink() {
766 // MariaDB includes its name in its version string (sent when the connection is opened),
767 // and this is how MariaDB's version of the mysql command-line client identifies MariaDB
768 // servers (see the mariadb_connection() function in libmysql/libmysql.c).
769 $version = $this->getServerVersion();
770 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
771 return '[{{int:version-db-mariadb-url}} MariaDB]';
774 // Percona Server's version suffix is not very distinctive, and @@version_comment
775 // doesn't give the necessary info for source builds, so assume the server is MySQL.
776 // (Even Percona's version of mysql doesn't try to make the distinction.)
777 return '[{{int:version-db-mysql-url}} MySQL]';
781 * @param array $options
783 public function setSessionOptions( array $options ) {
784 if ( isset( $options['connTimeout'] ) ) {
785 $timeout = (int)$options['connTimeout'];
786 $this->query( "SET net_read_timeout=$timeout" );
787 $this->query( "SET net_write_timeout=$timeout" );
792 * @param string $sql
793 * @param string $newLine
794 * @return bool
796 public function streamStatementEnd( &$sql, &$newLine ) {
797 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
798 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
799 $this->delimiter = $m[1];
800 $newLine = '';
803 return parent::streamStatementEnd( $sql, $newLine );
807 * Check to see if a named lock is available. This is non-blocking.
809 * @param string $lockName name of lock to poll
810 * @param string $method name of method calling us
811 * @return bool
812 * @since 1.20
814 public function lockIsFree( $lockName, $method ) {
815 $lockName = $this->addQuotes( $lockName );
816 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
817 $row = $this->fetchObject( $result );
819 return ( $row->lockstatus == 1 );
823 * @param string $lockName
824 * @param string $method
825 * @param int $timeout
826 * @return bool
828 public function lock( $lockName, $method, $timeout = 5 ) {
829 $lockName = $this->addQuotes( $lockName );
830 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
831 $row = $this->fetchObject( $result );
833 if ( $row->lockstatus == 1 ) {
834 return true;
835 } else {
836 wfDebug( __METHOD__ . " failed to acquire lock\n" );
838 return false;
843 * FROM MYSQL DOCS:
844 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
845 * @param string $lockName
846 * @param string $method
847 * @return bool
849 public function unlock( $lockName, $method ) {
850 $lockName = $this->addQuotes( $lockName );
851 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
852 $row = $this->fetchObject( $result );
854 return ( $row->lockstatus == 1 );
858 * @param array $read
859 * @param array $write
860 * @param string $method
861 * @param bool $lowPriority
862 * @return bool
864 public function lockTables( $read, $write, $method, $lowPriority = true ) {
865 $items = array();
867 foreach ( $write as $table ) {
868 $tbl = $this->tableName( $table ) .
869 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
870 ' WRITE';
871 $items[] = $tbl;
873 foreach ( $read as $table ) {
874 $items[] = $this->tableName( $table ) . ' READ';
876 $sql = "LOCK TABLES " . implode( ',', $items );
877 $this->query( $sql, $method );
879 return true;
883 * @param string $method
884 * @return bool
886 public function unlockTables( $method ) {
887 $this->query( "UNLOCK TABLES", $method );
889 return true;
893 * Get search engine class. All subclasses of this
894 * need to implement this if they wish to use searching.
896 * @return string
898 public function getSearchEngine() {
899 return 'SearchMySQL';
903 * @param bool $value
904 * @return mixed null|bool|ResultWrapper
906 public function setBigSelects( $value = true ) {
907 if ( $value === 'default' ) {
908 if ( $this->mDefaultBigSelects === null ) {
909 # Function hasn't been called before so it must already be set to the default
910 return;
911 } else {
912 $value = $this->mDefaultBigSelects;
914 } elseif ( $this->mDefaultBigSelects === null ) {
915 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
917 $encValue = $value ? '1' : '0';
918 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
922 * DELETE where the condition is a join. MySql uses multi-table deletes.
923 * @param string $delTable
924 * @param string $joinTable
925 * @param string $delVar
926 * @param string $joinVar
927 * @param array|string $conds
928 * @param bool|string $fname
929 * @throws DBUnexpectedError
930 * @return bool|ResultWrapper
932 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
933 if ( !$conds ) {
934 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
937 $delTable = $this->tableName( $delTable );
938 $joinTable = $this->tableName( $joinTable );
939 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
941 if ( $conds != '*' ) {
942 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
945 return $this->query( $sql, $fname );
949 * @param string $table
950 * @param array $rows
951 * @param array $uniqueIndexes
952 * @param array $set
953 * @param string $fname
954 * @return bool
956 public function upsert( $table, array $rows, array $uniqueIndexes,
957 array $set, $fname = __METHOD__
959 if ( !count( $rows ) ) {
960 return true; // nothing to do
963 if ( !is_array( reset( $rows ) ) ) {
964 $rows = array( $rows );
967 $table = $this->tableName( $table );
968 $columns = array_keys( $rows[0] );
970 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
971 $rowTuples = array();
972 foreach ( $rows as $row ) {
973 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
975 $sql .= implode( ',', $rowTuples );
976 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
978 return (bool)$this->query( $sql, $fname );
982 * Determines how long the server has been up
984 * @return int
986 function getServerUptime() {
987 $vars = $this->getMysqlStatus( 'Uptime' );
989 return (int)$vars['Uptime'];
993 * Determines if the last failure was due to a deadlock
995 * @return bool
997 function wasDeadlock() {
998 return $this->lastErrno() == 1213;
1002 * Determines if the last failure was due to a lock timeout
1004 * @return bool
1006 function wasLockTimeout() {
1007 return $this->lastErrno() == 1205;
1011 * Determines if the last query error was something that should be dealt
1012 * with by pinging the connection and reissuing the query
1014 * @return bool
1016 function wasErrorReissuable() {
1017 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1021 * Determines if the last failure was due to the database being read-only.
1023 * @return bool
1025 function wasReadOnlyError() {
1026 return $this->lastErrno() == 1223 ||
1027 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1031 * @param string $oldName
1032 * @param string $newName
1033 * @param bool $temporary
1034 * @param string $fname
1035 * @return bool
1037 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1038 $tmp = $temporary ? 'TEMPORARY ' : '';
1039 $newName = $this->addIdentifierQuotes( $newName );
1040 $oldName = $this->addIdentifierQuotes( $oldName );
1041 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1043 return $this->query( $query, $fname );
1047 * List all tables on the database
1049 * @param string $prefix Only show tables with this prefix, e.g. mw_
1050 * @param string $fname Calling function name
1051 * @return array
1053 function listTables( $prefix = null, $fname = __METHOD__ ) {
1054 $result = $this->query( "SHOW TABLES", $fname );
1056 $endArray = array();
1058 foreach ( $result as $table ) {
1059 $vars = get_object_vars( $table );
1060 $table = array_pop( $vars );
1062 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1063 $endArray[] = $table;
1067 return $endArray;
1071 * @param string $tableName
1072 * @param string $fName
1073 * @return bool|ResultWrapper
1075 public function dropTable( $tableName, $fName = __METHOD__ ) {
1076 if ( !$this->tableExists( $tableName, $fName ) ) {
1077 return false;
1080 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1084 * @return array
1086 protected function getDefaultSchemaVars() {
1087 $vars = parent::getDefaultSchemaVars();
1088 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1089 $vars['wgDBTableOptions'] = str_replace(
1090 'CHARSET=mysql4',
1091 'CHARSET=binary',
1092 $vars['wgDBTableOptions']
1095 return $vars;
1099 * Get status information from SHOW STATUS in an associative array
1101 * @param string $which
1102 * @return array
1104 function getMysqlStatus( $which = "%" ) {
1105 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1106 $status = array();
1108 foreach ( $res as $row ) {
1109 $status[$row->Variable_name] = $row->Value;
1112 return $status;
1116 * Lists VIEWs in the database
1118 * @param string $prefix Only show VIEWs with this prefix, eg.
1119 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1120 * @param string $fname Name of calling function
1121 * @return array
1122 * @since 1.22
1124 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1126 if ( !isset( $this->allViews ) ) {
1128 // The name of the column containing the name of the VIEW
1129 $propertyName = 'Tables_in_' . $this->mDBname;
1131 // Query for the VIEWS
1132 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1133 $this->allViews = array();
1134 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1135 array_push( $this->allViews, $row[$propertyName] );
1139 if ( is_null( $prefix ) || $prefix === '' ) {
1140 return $this->allViews;
1143 $filteredViews = array();
1144 foreach ( $this->allViews as $viewName ) {
1145 // Does the name of this VIEW start with the table-prefix?
1146 if ( strpos( $viewName, $prefix ) === 0 ) {
1147 array_push( $filteredViews, $viewName );
1151 return $filteredViews;
1155 * Differentiates between a TABLE and a VIEW.
1157 * @param string $name Name of the TABLE/VIEW to test
1158 * @param string $prefix
1159 * @return bool
1160 * @since 1.22
1162 public function isView( $name, $prefix = null ) {
1163 return in_array( $name, $this->listViews( $prefix ) );
1168 * Utility class.
1169 * @ingroup Database
1171 class MySQLField implements Field {
1172 private $name, $tablename, $default, $max_length, $nullable,
1173 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1175 function __construct( $info ) {
1176 $this->name = $info->name;
1177 $this->tablename = $info->table;
1178 $this->default = $info->def;
1179 $this->max_length = $info->max_length;
1180 $this->nullable = !$info->not_null;
1181 $this->is_pk = $info->primary_key;
1182 $this->is_unique = $info->unique_key;
1183 $this->is_multiple = $info->multiple_key;
1184 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1185 $this->type = $info->type;
1186 $this->binary = isset( $info->binary ) ? $info->binary : false;
1190 * @return string
1192 function name() {
1193 return $this->name;
1197 * @return string
1199 function tableName() {
1200 return $this->tableName;
1204 * @return string
1206 function type() {
1207 return $this->type;
1211 * @return bool
1213 function isNullable() {
1214 return $this->nullable;
1217 function defaultValue() {
1218 return $this->default;
1222 * @return bool
1224 function isKey() {
1225 return $this->is_key;
1229 * @return bool
1231 function isMultipleKey() {
1232 return $this->is_multiple;
1235 function isBinary() {
1236 return $this->binary;
1240 class MySQLMasterPos implements DBMasterPos {
1241 /** @var string */
1242 public $file;
1244 /** @var int timestamp */
1245 public $pos;
1247 function __construct( $file, $pos ) {
1248 $this->file = $file;
1249 $this->pos = $pos;
1252 function __toString() {
1253 // e.g db1034-bin.000976/843431247
1254 return "{$this->file}/{$this->pos}";
1258 * @return array|bool (int, int)
1260 protected function getCoordinates() {
1261 $m = array();
1262 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1263 return array( (int)$m[1], (int)$m[2] );
1266 return false;
1269 function hasReached( MySQLMasterPos $pos ) {
1270 $thisPos = $this->getCoordinates();
1271 $thatPos = $pos->getCoordinates();
1273 return ( $thisPos && $thatPos && $thisPos >= $thatPos );