MediaWiki PHP Cross Reference Collaborative Wikis

Source: /includes/db/DatabaseMysqlBase.php - 1161 lines - 29052 bytes - Summary - Text - Print

Description: This is the MySQL database abstraction layer. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

   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  
  36      /**
  37       * @return string
  38       */
  39  	function getType() {
  40          return 'mysql';
  41      }
  42  
  43      /**
  44       * @param $server string
  45       * @param $user string
  46       * @param $password string
  47       * @param $dbName string
  48       * @return bool
  49       * @throws DBConnectionError
  50       */
  51  	function open( $server, $user, $password, $dbName ) {
  52          global $wgAllDBsAreLocalhost, $wgDBmysql5, $wgSQLMode;
  53          wfProfileIn( __METHOD__ );
  54  
  55          # Debugging hack -- fake cluster
  56          if ( $wgAllDBsAreLocalhost ) {
  57              $realServer = 'localhost';
  58          } else {
  59              $realServer = $server;
  60          }
  61          $this->close();
  62          $this->mServer = $server;
  63          $this->mUser = $user;
  64          $this->mPassword = $password;
  65          $this->mDBname = $dbName;
  66  
  67          wfProfileIn( "dbconnect-$server" );
  68  
  69          # The kernel's default SYN retransmission period is far too slow for us,
  70          # so we use a short timeout plus a manual retry. Retrying means that a small
  71          # but finite rate of SYN packet loss won't cause user-visible errors.
  72          $this->mConn = false;
  73          $this->installErrorHandler();
  74          try {
  75              $this->mConn = $this->mysqlConnect( $realServer );
  76          } catch ( Exception $ex ) {
  77              wfProfileOut( "dbconnect-$server" );
  78              wfProfileOut( __METHOD__ );
  79              throw $ex;
  80          }
  81          $error = $this->restoreErrorHandler();
  82  
  83          wfProfileOut( "dbconnect-$server" );
  84  
  85          # Always log connection errors
  86          if ( !$this->mConn ) {
  87              if ( !$error ) {
  88                  $error = $this->lastError();
  89              }
  90              wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
  91              wfDebug( "DB connection error\n" .
  92                  "Server: $server, User: $user, Password: " .
  93                  substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
  94  
  95              wfProfileOut( __METHOD__ );
  96              return $this->reportConnectionError( $error );
  97          }
  98  
  99          if ( $dbName != '' ) {
 100              wfSuppressWarnings();
 101              $success = $this->selectDB( $dbName );
 102              wfRestoreWarnings();
 103              if ( !$success ) {
 104                  wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
 105                  wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
 106                      "from client host " . wfHostname() . "\n" );
 107  
 108                  wfProfileOut( __METHOD__ );
 109                  return $this->reportConnectionError( "Error selecting database $dbName" );
 110              }
 111          }
 112  
 113          // Tell the server we're communicating with it in UTF-8.
 114          // This may engage various charset conversions.
 115          if ( $wgDBmysql5 ) {
 116              $this->query( 'SET NAMES utf8', __METHOD__ );
 117          } else {
 118              $this->query( 'SET NAMES binary', __METHOD__ );
 119          }
 120          // Set SQL mode, default is turning them all off, can be overridden or skipped with null
 121          if ( is_string( $wgSQLMode ) ) {
 122              $mode = $this->addQuotes( $wgSQLMode );
 123              $this->query( "SET sql_mode = $mode", __METHOD__ );
 124          }
 125  
 126          $this->mOpened = true;
 127          wfProfileOut( __METHOD__ );
 128          return true;
 129      }
 130  
 131      /**
 132       * Open a connection to a MySQL server
 133       *
 134       * @param $realServer string
 135       * @return mixed Raw connection
 136       * @throws DBConnectionError
 137       */
 138      abstract protected function mysqlConnect( $realServer );
 139  
 140      /**
 141       * @param $res ResultWrapper
 142       * @throws DBUnexpectedError
 143       */
 144  	function freeResult( $res ) {
 145          if ( $res instanceof ResultWrapper ) {
 146              $res = $res->result;
 147          }
 148          wfSuppressWarnings();
 149          $ok = $this->mysqlFreeResult( $res );
 150          wfRestoreWarnings();
 151          if ( !$ok ) {
 152              throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
 153          }
 154      }
 155  
 156      /**
 157       * Free result memory
 158       *
 159       * @param $res Raw result
 160       * @return bool
 161       */
 162      abstract protected function mysqlFreeResult( $res );
 163  
 164      /**
 165       * @param $res ResultWrapper
 166       * @return object|bool
 167       * @throws DBUnexpectedError
 168       */
 169  	function fetchObject( $res ) {
 170          if ( $res instanceof ResultWrapper ) {
 171              $res = $res->result;
 172          }
 173          wfSuppressWarnings();
 174          $row = $this->mysqlFetchObject( $res );
 175          wfRestoreWarnings();
 176  
 177          $errno = $this->lastErrno();
 178          // Unfortunately, mysql_fetch_object does not reset the last errno.
 179          // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
 180          // these are the only errors mysql_fetch_object can cause.
 181          // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
 182          if ( $errno == 2000 || $errno == 2013 ) {
 183              throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
 184          }
 185          return $row;
 186      }
 187  
 188      /**
 189       * Fetch a result row as an object
 190       *
 191       * @param $res Raw result
 192       * @return stdClass
 193       */
 194      abstract protected function mysqlFetchObject( $res );
 195  
 196      /**
 197       * @param $res ResultWrapper
 198       * @return array|bool
 199       * @throws DBUnexpectedError
 200       */
 201  	function fetchRow( $res ) {
 202          if ( $res instanceof ResultWrapper ) {
 203              $res = $res->result;
 204          }
 205          wfSuppressWarnings();
 206          $row = $this->mysqlFetchArray( $res );
 207          wfRestoreWarnings();
 208  
 209          $errno = $this->lastErrno();
 210          // Unfortunately, mysql_fetch_array does not reset the last errno.
 211          // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
 212          // these are the only errors mysql_fetch_array can cause.
 213          // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
 214          if ( $errno == 2000 || $errno == 2013 ) {
 215              throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
 216          }
 217          return $row;
 218      }
 219  
 220      /**
 221       * Fetch a result row as an associative and numeric array
 222       *
 223       * @param $res Raw result
 224       * @return array
 225       */
 226      abstract protected function mysqlFetchArray( $res );
 227  
 228      /**
 229       * @throws DBUnexpectedError
 230       * @param $res ResultWrapper
 231       * @return int
 232       */
 233  	function numRows( $res ) {
 234          if ( $res instanceof ResultWrapper ) {
 235              $res = $res->result;
 236          }
 237          wfSuppressWarnings();
 238          $n = $this->mysqlNumRows( $res );
 239          wfRestoreWarnings();
 240          // Unfortunately, mysql_num_rows does not reset the last errno.
 241          // We are not checking for any errors here, since
 242          // these are no errors mysql_num_rows can cause.
 243          // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
 244          // See https://bugzilla.wikimedia.org/42430
 245          return $n;
 246      }
 247  
 248      /**
 249       * Get number of rows in result
 250       *
 251       * @param $res Raw result
 252       * @return int
 253       */
 254      abstract protected function mysqlNumRows( $res );
 255  
 256      /**
 257       * @param $res ResultWrapper
 258       * @return int
 259       */
 260  	function numFields( $res ) {
 261          if ( $res instanceof ResultWrapper ) {
 262              $res = $res->result;
 263          }
 264          return $this->mysqlNumFields( $res );
 265      }
 266  
 267      /**
 268       * Get number of fields in result
 269       *
 270       * @param $res Raw result
 271       * @return int
 272       */
 273      abstract protected function mysqlNumFields( $res );
 274  
 275      /**
 276       * @param $res ResultWrapper
 277       * @param $n string
 278       * @return string
 279       */
 280  	function fieldName( $res, $n ) {
 281          if ( $res instanceof ResultWrapper ) {
 282              $res = $res->result;
 283          }
 284          return $this->mysqlFieldName( $res, $n );
 285      }
 286  
 287      /**
 288       * Get the name of the specified field in a result
 289       *
 290       * @param $res Raw result
 291       * @param $n int
 292       * @return string
 293       */
 294      abstract protected function mysqlFieldName( $res, $n );
 295  
 296      /**
 297       * @param $res ResultWrapper
 298       * @param $row
 299       * @return bool
 300       */
 301  	function dataSeek( $res, $row ) {
 302          if ( $res instanceof ResultWrapper ) {
 303              $res = $res->result;
 304          }
 305          return $this->mysqlDataSeek( $res, $row );
 306      }
 307  
 308      /**
 309       * Move internal result pointer
 310       *
 311       * @param $res Raw result
 312       * @param $row int
 313       * @return bool
 314       */
 315      abstract protected function mysqlDataSeek( $res, $row );
 316  
 317      /**
 318       * @return string
 319       */
 320  	function lastError() {
 321          if ( $this->mConn ) {
 322              # Even if it's non-zero, it can still be invalid
 323              wfSuppressWarnings();
 324              $error = $this->mysqlError( $this->mConn );
 325              if ( !$error ) {
 326                  $error = $this->mysqlError();
 327              }
 328              wfRestoreWarnings();
 329          } else {
 330              $error = $this->mysqlError();
 331          }
 332          if ( $error ) {
 333              $error .= ' (' . $this->mServer . ')';
 334          }
 335          return $error;
 336      }
 337  
 338      /**
 339       * Returns the text of the error message from previous MySQL operation
 340       *
 341       * @param $conn Raw connection
 342       * @return string
 343       */
 344      abstract protected function mysqlError( $conn = null );
 345  
 346      /**
 347       * @param $table string
 348       * @param $uniqueIndexes
 349       * @param $rows array
 350       * @param $fname string
 351       * @return ResultWrapper
 352       */
 353  	function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
 354          return $this->nativeReplace( $table, $rows, $fname );
 355      }
 356  
 357      /**
 358       * Estimate rows in dataset
 359       * Returns estimated count, based on EXPLAIN output
 360       * Takes same arguments as Database::select()
 361       *
 362       * @param $table string|array
 363       * @param $vars string|array
 364       * @param $conds string|array
 365       * @param $fname string
 366       * @param $options string|array
 367       * @return int
 368       */
 369  	public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array() ) {
 370          $options['EXPLAIN'] = true;
 371          $res = $this->select( $table, $vars, $conds, $fname, $options );
 372          if ( $res === false ) {
 373              return false;
 374          }
 375          if ( !$this->numRows( $res ) ) {
 376              return 0;
 377          }
 378  
 379          $rows = 1;
 380          foreach ( $res as $plan ) {
 381              $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
 382          }
 383          return $rows;
 384      }
 385  
 386      /**
 387       * @param $table string
 388       * @param $field string
 389       * @return bool|MySQLField
 390       */
 391  	function fieldInfo( $table, $field ) {
 392          $table = $this->tableName( $table );
 393          $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
 394          if ( !$res ) {
 395              return false;
 396          }
 397          $n = $this->mysqlNumFields( $res->result );
 398          for ( $i = 0; $i < $n; $i++ ) {
 399              $meta = $this->mysqlFetchField( $res->result, $i );
 400              if ( $field == $meta->name ) {
 401                  return new MySQLField( $meta );
 402              }
 403          }
 404          return false;
 405      }
 406  
 407      /**
 408       * Get column information from a result
 409       *
 410       * @param $res Raw result
 411       * @param $n int
 412       * @return stdClass
 413       */
 414      abstract protected function mysqlFetchField( $res, $n );
 415  
 416      /**
 417       * Get information about an index into an object
 418       * Returns false if the index does not exist
 419       *
 420       * @param $table string
 421       * @param $index string
 422       * @param $fname string
 423       * @return bool|array|null False or null on failure
 424       */
 425  	function indexInfo( $table, $index, $fname = __METHOD__ ) {
 426          # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
 427          # SHOW INDEX should work for 3.x and up:
 428          # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
 429          $table = $this->tableName( $table );
 430          $index = $this->indexName( $index );
 431  
 432          $sql = 'SHOW INDEX FROM ' . $table;
 433          $res = $this->query( $sql, $fname );
 434  
 435          if ( !$res ) {
 436              return null;
 437          }
 438  
 439          $result = array();
 440  
 441          foreach ( $res as $row ) {
 442              if ( $row->Key_name == $index ) {
 443                  $result[] = $row;
 444              }
 445          }
 446          return empty( $result ) ? false : $result;
 447      }
 448  
 449      /**
 450       * @param $s string
 451       *
 452       * @return string
 453       */
 454  	function strencode( $s ) {
 455          $sQuoted = $this->mysqlRealEscapeString( $s );
 456  
 457          if ( $sQuoted === false ) {
 458              $this->ping();
 459              $sQuoted = $this->mysqlRealEscapeString( $s );
 460          }
 461          return $sQuoted;
 462      }
 463  
 464      /**
 465       * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
 466       *
 467       * @param $s string
 468       *
 469       * @return string
 470       */
 471  	public function addIdentifierQuotes( $s ) {
 472          // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
 473          // Remove NUL bytes and escape backticks by doubling
 474          return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s )  . '`';
 475      }
 476  
 477      /**
 478       * @param $name string
 479       * @return bool
 480       */
 481  	public function isQuotedIdentifier( $name ) {
 482          return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
 483      }
 484  
 485      /**
 486       * @return bool
 487       */
 488  	function ping() {
 489          $ping = $this->mysqlPing();
 490          if ( $ping ) {
 491              return true;
 492          }
 493  
 494          $this->closeConnection();
 495          $this->mOpened = false;
 496          $this->mConn = false;
 497          $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
 498          return true;
 499      }
 500  
 501      /**
 502       * Ping a server connection or reconnect if there is no connection
 503       *
 504       * @return bool
 505       */
 506      abstract protected function mysqlPing();
 507  
 508      /**
 509       * Returns slave lag.
 510       *
 511       * This will do a SHOW SLAVE STATUS
 512       *
 513       * @return int
 514       */
 515  	function getLag() {
 516          if ( !is_null( $this->mFakeSlaveLag ) ) {
 517              wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
 518              return $this->mFakeSlaveLag;
 519          }
 520  
 521          return $this->getLagFromSlaveStatus();
 522      }
 523  
 524      /**
 525       * @return bool|int
 526       */
 527  	function getLagFromSlaveStatus() {
 528          $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
 529          if ( !$res ) {
 530              return false;
 531          }
 532          $row = $res->fetchObject();
 533          if ( !$row ) {
 534              return false;
 535          }
 536          if ( strval( $row->Seconds_Behind_Master ) === '' ) {
 537              return false;
 538          } else {
 539              return intval( $row->Seconds_Behind_Master );
 540          }
 541      }
 542  
 543      /**
 544       * @deprecated in 1.19, use getLagFromSlaveStatus
 545       *
 546       * @return bool|int
 547       */
 548  	function getLagFromProcesslist() {
 549          wfDeprecated( __METHOD__, '1.19' );
 550          $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
 551          if ( !$res ) {
 552              return false;
 553          }
 554          # Find slave SQL thread
 555          foreach ( $res as $row ) {
 556              /* This should work for most situations - when default db
 557               * for thread is not specified, it had no events executed,
 558               * and therefore it doesn't know yet how lagged it is.
 559               *
 560               * Relay log I/O thread does not select databases.
 561               */
 562              if ( $row->User == 'system user' &&
 563                  $row->State != 'Waiting for master to send event' &&
 564                  $row->State != 'Connecting to master' &&
 565                  $row->State != 'Queueing master event to the relay log' &&
 566                  $row->State != 'Waiting for master update' &&
 567                  $row->State != 'Requesting binlog dump' &&
 568                  $row->State != 'Waiting to reconnect after a failed master event read' &&
 569                  $row->State != 'Reconnecting after a failed master event read' &&
 570                  $row->State != 'Registering slave on master'
 571                  ) {
 572                  # This is it, return the time (except -ve)
 573                  if ( $row->Time > 0x7fffffff ) {
 574                      return false;
 575                  } else {
 576                      return $row->Time;
 577                  }
 578              }
 579          }
 580          return false;
 581      }
 582  
 583      /**
 584       * Wait for the slave to catch up to a given master position.
 585       * @TODO: return values for this and base class are rubbish
 586       *
 587       * @param $pos DBMasterPos object
 588       * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
 589       * @return bool|string
 590       */
 591  	function masterPosWait( DBMasterPos $pos, $timeout ) {
 592          if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
 593              return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
 594          }
 595  
 596          wfProfileIn( __METHOD__ );
 597          # Commit any open transactions
 598          $this->commit( __METHOD__, 'flush' );
 599  
 600          if ( !is_null( $this->mFakeSlaveLag ) ) {
 601              $status = parent::masterPosWait( $pos, $timeout );
 602              wfProfileOut( __METHOD__ );
 603              return $status;
 604          }
 605  
 606          # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
 607          $encFile = $this->addQuotes( $pos->file );
 608          $encPos = intval( $pos->pos );
 609          $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
 610          $res = $this->doQuery( $sql );
 611  
 612          $status = false;
 613          if ( $res && $row = $this->fetchRow( $res ) ) {
 614              $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
 615              if ( ctype_digit( $status ) ) { // success
 616                  $this->lastKnownSlavePos = $pos;
 617              }
 618          }
 619  
 620          wfProfileOut( __METHOD__ );
 621          return $status;
 622      }
 623  
 624      /**
 625       * Get the position of the master from SHOW SLAVE STATUS
 626       *
 627       * @return MySQLMasterPos|bool
 628       */
 629  	function getSlavePos() {
 630          if ( !is_null( $this->mFakeSlaveLag ) ) {
 631              return parent::getSlavePos();
 632          }
 633  
 634          $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
 635          $row = $this->fetchObject( $res );
 636  
 637          if ( $row ) {
 638              $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
 639              return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
 640          } else {
 641              return false;
 642          }
 643      }
 644  
 645      /**
 646       * Get the position of the master from SHOW MASTER STATUS
 647       *
 648       * @return MySQLMasterPos|bool
 649       */
 650  	function getMasterPos() {
 651          if ( $this->mFakeMaster ) {
 652              return parent::getMasterPos();
 653          }
 654  
 655          $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
 656          $row = $this->fetchObject( $res );
 657  
 658          if ( $row ) {
 659              return new MySQLMasterPos( $row->File, $row->Position );
 660          } else {
 661              return false;
 662          }
 663      }
 664  
 665      /**
 666       * @param $index
 667       * @return string
 668       */
 669  	function useIndexClause( $index ) {
 670          return "FORCE INDEX (" . $this->indexName( $index ) . ")";
 671      }
 672  
 673      /**
 674       * @return string
 675       */
 676  	function lowPriorityOption() {
 677          return 'LOW_PRIORITY';
 678      }
 679  
 680      /**
 681       * @return string
 682       */
 683  	public function getSoftwareLink() {
 684          $version = $this->getServerVersion();
 685          if ( strpos( $version, 'MariaDB' ) !== false ) {
 686              return '[{{int:version-db-mariadb-url}} MariaDB]';
 687          } elseif ( strpos( $version, 'percona' ) !== false ) {
 688              return '[{{int:version-db-percona-url}} Percona Server]';
 689          } else {
 690              return '[{{int:version-db-mysql-url}} MySQL]';
 691          }
 692      }
 693  
 694      /**
 695       * @param $options array
 696       */
 697  	public function setSessionOptions( array $options ) {
 698          if ( isset( $options['connTimeout'] ) ) {
 699              $timeout = (int)$options['connTimeout'];
 700              $this->query( "SET net_read_timeout=$timeout" );
 701              $this->query( "SET net_write_timeout=$timeout" );
 702          }
 703      }
 704  
 705  	public function streamStatementEnd( &$sql, &$newLine ) {
 706          if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
 707              preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
 708              $this->delimiter = $m[1];
 709              $newLine = '';
 710          }
 711          return parent::streamStatementEnd( $sql, $newLine );
 712      }
 713  
 714      /**
 715       * Check to see if a named lock is available. This is non-blocking.
 716       *
 717       * @param string $lockName name of lock to poll
 718       * @param string $method name of method calling us
 719       * @return Boolean
 720       * @since 1.20
 721       */
 722  	public function lockIsFree( $lockName, $method ) {
 723          $lockName = $this->addQuotes( $lockName );
 724          $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
 725          $row = $this->fetchObject( $result );
 726          return ( $row->lockstatus == 1 );
 727      }
 728  
 729      /**
 730       * @param $lockName string
 731       * @param $method string
 732       * @param $timeout int
 733       * @return bool
 734       */
 735  	public function lock( $lockName, $method, $timeout = 5 ) {
 736          $lockName = $this->addQuotes( $lockName );
 737          $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
 738          $row = $this->fetchObject( $result );
 739  
 740          if ( $row->lockstatus == 1 ) {
 741              return true;
 742          } else {
 743              wfDebug( __METHOD__ . " failed to acquire lock\n" );
 744              return false;
 745          }
 746      }
 747  
 748      /**
 749       * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
 750       * @param $lockName string
 751       * @param $method string
 752       * @return bool
 753       */
 754  	public function unlock( $lockName, $method ) {
 755          $lockName = $this->addQuotes( $lockName );
 756          $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
 757          $row = $this->fetchObject( $result );
 758          return ( $row->lockstatus == 1 );
 759      }
 760  
 761      /**
 762       * @param $read array
 763       * @param $write array
 764       * @param $method string
 765       * @param $lowPriority bool
 766       * @return bool
 767       */
 768  	public function lockTables( $read, $write, $method, $lowPriority = true ) {
 769          $items = array();
 770  
 771          foreach ( $write as $table ) {
 772              $tbl = $this->tableName( $table ) .
 773                      ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
 774                      ' WRITE';
 775              $items[] = $tbl;
 776          }
 777          foreach ( $read as $table ) {
 778              $items[] = $this->tableName( $table ) . ' READ';
 779          }
 780          $sql = "LOCK TABLES " . implode( ',', $items );
 781          $this->query( $sql, $method );
 782          return true;
 783      }
 784  
 785      /**
 786       * @param $method string
 787       * @return bool
 788       */
 789  	public function unlockTables( $method ) {
 790          $this->query( "UNLOCK TABLES", $method );
 791          return true;
 792      }
 793  
 794      /**
 795       * Get search engine class. All subclasses of this
 796       * need to implement this if they wish to use searching.
 797       *
 798       * @return String
 799       */
 800  	public function getSearchEngine() {
 801          return 'SearchMySQL';
 802      }
 803  
 804      /**
 805       * @param bool $value
 806       * @return mixed
 807       */
 808  	public function setBigSelects( $value = true ) {
 809          if ( $value === 'default' ) {
 810              if ( $this->mDefaultBigSelects === null ) {
 811                  # Function hasn't been called before so it must already be set to the default
 812                  return;
 813              } else {
 814                  $value = $this->mDefaultBigSelects;
 815              }
 816          } elseif ( $this->mDefaultBigSelects === null ) {
 817              $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
 818          }
 819          $encValue = $value ? '1' : '0';
 820          $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
 821      }
 822  
 823      /**
 824       * DELETE where the condition is a join. MySql uses multi-table deletes.
 825       * @param $delTable string
 826       * @param $joinTable string
 827       * @param $delVar string
 828       * @param $joinVar string
 829       * @param $conds array|string
 830       * @param bool|string $fname bool
 831       * @throws DBUnexpectedError
 832       * @return bool|ResultWrapper
 833       */
 834  	function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
 835          if ( !$conds ) {
 836              throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
 837          }
 838  
 839          $delTable = $this->tableName( $delTable );
 840          $joinTable = $this->tableName( $joinTable );
 841          $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
 842  
 843          if ( $conds != '*' ) {
 844              $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
 845          }
 846  
 847          return $this->query( $sql, $fname );
 848      }
 849  
 850      /**
 851       * @param string $table
 852       * @param array $rows
 853       * @param array $uniqueIndexes
 854       * @param array $set
 855       * @param string $fname
 856       * @param array $options
 857       * @return bool
 858       */
 859  	public function upsert(
 860          $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
 861      ) {
 862          if ( !count( $rows ) ) {
 863              return true; // nothing to do
 864          }
 865          $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
 866  
 867          $table = $this->tableName( $table );
 868          $columns = array_keys( $rows[0] );
 869  
 870          $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
 871          $rowTuples = array();
 872          foreach ( $rows as $row ) {
 873              $rowTuples[] = '(' . $this->makeList( $row ) . ')';
 874          }
 875          $sql .= implode( ',', $rowTuples );
 876          $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
 877  
 878          return (bool)$this->query( $sql, $fname );
 879      }
 880  
 881      /**
 882       * Determines how long the server has been up
 883       *
 884       * @return int
 885       */
 886  	function getServerUptime() {
 887          $vars = $this->getMysqlStatus( 'Uptime' );
 888          return (int)$vars['Uptime'];
 889      }
 890  
 891      /**
 892       * Determines if the last failure was due to a deadlock
 893       *
 894       * @return bool
 895       */
 896  	function wasDeadlock() {
 897          return $this->lastErrno() == 1213;
 898      }
 899  
 900      /**
 901       * Determines if the last failure was due to a lock timeout
 902       *
 903       * @return bool
 904       */
 905  	function wasLockTimeout() {
 906          return $this->lastErrno() == 1205;
 907      }
 908  
 909      /**
 910       * Determines if the last query error was something that should be dealt
 911       * with by pinging the connection and reissuing the query
 912       *
 913       * @return bool
 914       */
 915  	function wasErrorReissuable() {
 916          return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
 917      }
 918  
 919      /**
 920       * Determines if the last failure was due to the database being read-only.
 921       *
 922       * @return bool
 923       */
 924  	function wasReadOnlyError() {
 925          return $this->lastErrno() == 1223 ||
 926              ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
 927      }
 928  
 929      /**
 930       * @param $oldName
 931       * @param $newName
 932       * @param $temporary bool
 933       * @param $fname string
 934       */
 935  	function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
 936          $tmp = $temporary ? 'TEMPORARY ' : '';
 937          $newName = $this->addIdentifierQuotes( $newName );
 938          $oldName = $this->addIdentifierQuotes( $oldName );
 939          $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
 940          $this->query( $query, $fname );
 941      }
 942  
 943      /**
 944       * List all tables on the database
 945       *
 946       * @param string $prefix Only show tables with this prefix, e.g. mw_
 947       * @param string $fname calling function name
 948       * @return array
 949       */
 950  	function listTables( $prefix = null, $fname = __METHOD__ ) {
 951          $result = $this->query( "SHOW TABLES", $fname );
 952  
 953          $endArray = array();
 954  
 955          foreach ( $result as $table ) {
 956              $vars = get_object_vars( $table );
 957              $table = array_pop( $vars );
 958  
 959              if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
 960                  $endArray[] = $table;
 961              }
 962          }
 963  
 964          return $endArray;
 965      }
 966  
 967      /**
 968       * @param $tableName
 969       * @param $fName string
 970       * @return bool|ResultWrapper
 971       */
 972  	public function dropTable( $tableName, $fName = __METHOD__ ) {
 973          if ( !$this->tableExists( $tableName, $fName ) ) {
 974              return false;
 975          }
 976          return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
 977      }
 978  
 979      /**
 980       * @return array
 981       */
 982  	protected function getDefaultSchemaVars() {
 983          $vars = parent::getDefaultSchemaVars();
 984          $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
 985          $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
 986          return $vars;
 987      }
 988  
 989      /**
 990       * Get status information from SHOW STATUS in an associative array
 991       *
 992       * @param $which string
 993       * @return array
 994       */
 995  	function getMysqlStatus( $which = "%" ) {
 996          $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
 997          $status = array();
 998  
 999          foreach ( $res as $row ) {
1000              $status[$row->Variable_name] = $row->Value;
1001          }
1002  
1003          return $status;
1004      }
1005  
1006      /**
1007       * Lists VIEWs in the database
1008       *
1009       * @param string $prefix   Only show VIEWs with this prefix, eg.
1010       * unit_test_, or $wgDBprefix. Default: null, would return all views.
1011       * @param string $fname    Name of calling function
1012       * @return array
1013       * @since 1.22
1014       */
1015  	public function listViews( $prefix = null, $fname = __METHOD__ ) {
1016  
1017          if ( !isset( $this->allViews ) ) {
1018  
1019              // The name of the column containing the name of the VIEW
1020              $propertyName = 'Tables_in_' . $this->mDBname;
1021  
1022              // Query for the VIEWS
1023              $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1024              $this->allViews = array();
1025              while ( ($row = $this->fetchRow($result)) !== false ) {
1026                  array_push( $this->allViews, $row[$propertyName] );
1027              }
1028          }
1029  
1030          if ( is_null($prefix) || $prefix === '' ) {
1031              return $this->allViews;
1032          }
1033  
1034          $filteredViews = array();
1035          foreach ( $this->allViews as $viewName ) {
1036              // Does the name of this VIEW start with the table-prefix?
1037              if ( strpos( $viewName, $prefix ) === 0 ) {
1038                  array_push( $filteredViews, $viewName );
1039              }
1040          }
1041          return $filteredViews;
1042      }
1043  
1044      /**
1045       * Differentiates between a TABLE and a VIEW.
1046       *
1047       * @param $name string: Name of the TABLE/VIEW to test
1048       * @return bool
1049       * @since 1.22
1050       */
1051  	public function isView( $name, $prefix = null ) {
1052          return in_array( $name, $this->listViews( $prefix ) );
1053      }
1054  
1055  }
1056  
1057  
1058  
1059  /**
1060   * Utility class.
1061   * @ingroup Database
1062   */
1063  class MySQLField implements Field {
1064      private $name, $tablename, $default, $max_length, $nullable,
1065          $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1066  
1067  	function __construct( $info ) {
1068          $this->name = $info->name;
1069          $this->tablename = $info->table;
1070          $this->default = $info->def;
1071          $this->max_length = $info->max_length;
1072          $this->nullable = !$info->not_null;
1073          $this->is_pk = $info->primary_key;
1074          $this->is_unique = $info->unique_key;
1075          $this->is_multiple = $info->multiple_key;
1076          $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1077          $this->type = $info->type;
1078          $this->binary = isset( $info->binary ) ? $info->binary : false;
1079      }
1080  
1081      /**
1082       * @return string
1083       */
1084  	function name() {
1085          return $this->name;
1086      }
1087  
1088      /**
1089       * @return string
1090       */
1091  	function tableName() {
1092          return $this->tableName;
1093      }
1094  
1095      /**
1096       * @return string
1097       */
1098  	function type() {
1099          return $this->type;
1100      }
1101  
1102      /**
1103       * @return bool
1104       */
1105  	function isNullable() {
1106          return $this->nullable;
1107      }
1108  
1109  	function defaultValue() {
1110          return $this->default;
1111      }
1112  
1113      /**
1114       * @return bool
1115       */
1116  	function isKey() {
1117          return $this->is_key;
1118      }
1119  
1120      /**
1121       * @return bool
1122       */
1123  	function isMultipleKey() {
1124          return $this->is_multiple;
1125      }
1126  
1127  	function isBinary() {
1128          return $this->binary;
1129      }
1130  }
1131  
1132  class MySQLMasterPos implements DBMasterPos {
1133      var $file, $pos;
1134  
1135  	function __construct( $file, $pos ) {
1136          $this->file = $file;
1137          $this->pos = $pos;
1138      }
1139  
1140  	function __toString() {
1141          // e.g db1034-bin.000976/843431247
1142          return "{$this->file}/{$this->pos}";
1143      }
1144  
1145      /**
1146       * @return array|false (int, int)
1147       */
1148  	protected function getCoordinates() {
1149          $m = array();
1150          if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1151              return array( (int)$m[1], (int)$m[2] );
1152          }
1153          return false;
1154      }
1155  
1156  	function hasReached( MySQLMasterPos $pos ) {
1157          $thisPos = $this->getCoordinates();
1158          $thatPos = $pos->getCoordinates();
1159          return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1160      }
1161  }

title

Description

title

Description

title

Description

title

title

Body