/includes/db/Database.php
PHP | 3453 lines | 1361 code | 363 blank | 1729 comment | 286 complexity | 25cef59bff6341beb07882104ab8d1ed MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * @defgroup Database Database
- *
- * @file
- * @ingroup Database
- * This file deals with database interface functions
- * and query specifics/optimisations
- */
- /** Number of times to re-try an operation in case of deadlock */
- define( 'DEADLOCK_TRIES', 4 );
- /** Minimum time to wait before retry, in microseconds */
- define( 'DEADLOCK_DELAY_MIN', 500000 );
- /** Maximum time to wait before retry */
- define( 'DEADLOCK_DELAY_MAX', 1500000 );
- /**
- * Base interface for all DBMS-specific code. At a bare minimum, all of the
- * following must be implemented to support MediaWiki
- *
- * @file
- * @ingroup Database
- */
- interface DatabaseType {
- /**
- * Get the type of the DBMS, as it appears in $wgDBtype.
- *
- * @return string
- */
- function getType();
- /**
- * Open a connection to the database. Usually aborts on failure
- *
- * @param $server String: database server host
- * @param $user String: database user name
- * @param $password String: database user password
- * @param $dbName String: database name
- * @return bool
- * @throws DBConnectionError
- */
- function open( $server, $user, $password, $dbName );
- /**
- * Fetch the next row from the given result object, in object form.
- * Fields can be retrieved with $row->fieldname, with fields acting like
- * member variables.
- *
- * @param $res ResultWrapper|object as returned from DatabaseBase::query(), etc.
- * @return Row object
- * @throws DBUnexpectedError Thrown if the database returns an error
- */
- function fetchObject( $res );
- /**
- * Fetch the next row from the given result object, in associative array
- * form. Fields are retrieved with $row['fieldname'].
- *
- * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
- * @return Row object
- * @throws DBUnexpectedError Thrown if the database returns an error
- */
- function fetchRow( $res );
- /**
- * Get the number of rows in a result object
- *
- * @param $res Mixed: A SQL result
- * @return int
- */
- function numRows( $res );
- /**
- * Get the number of fields in a result object
- * @see http://www.php.net/mysql_num_fields
- *
- * @param $res Mixed: A SQL result
- * @return int
- */
- function numFields( $res );
- /**
- * Get a field name in a result object
- * @see http://www.php.net/mysql_field_name
- *
- * @param $res Mixed: A SQL result
- * @param $n Integer
- * @return string
- */
- function fieldName( $res, $n );
- /**
- * Get the inserted value of an auto-increment row
- *
- * The value inserted should be fetched from nextSequenceValue()
- *
- * Example:
- * $id = $dbw->nextSequenceValue('page_page_id_seq');
- * $dbw->insert('page',array('page_id' => $id));
- * $id = $dbw->insertId();
- *
- * @return int
- */
- function insertId();
- /**
- * Change the position of the cursor in a result object
- * @see http://www.php.net/mysql_data_seek
- *
- * @param $res Mixed: A SQL result
- * @param $row Mixed: Either MySQL row or ResultWrapper
- */
- function dataSeek( $res, $row );
- /**
- * Get the last error number
- * @see http://www.php.net/mysql_errno
- *
- * @return int
- */
- function lastErrno();
- /**
- * Get a description of the last error
- * @see http://www.php.net/mysql_error
- *
- * @return string
- */
- function lastError();
- /**
- * mysql_fetch_field() wrapper
- * Returns false if the field doesn't exist
- *
- * @param $table string: table name
- * @param $field string: field name
- *
- * @return Field
- */
- function fieldInfo( $table, $field );
- /**
- * Get information about an index into an object
- * @param $table string: Table name
- * @param $index string: Index name
- * @param $fname string: Calling function name
- * @return Mixed: Database-specific index description class or false if the index does not exist
- */
- function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
- /**
- * Get the number of rows affected by the last write query
- * @see http://www.php.net/mysql_affected_rows
- *
- * @return int
- */
- function affectedRows();
- /**
- * Wrapper for addslashes()
- *
- * @param $s string: to be slashed.
- * @return string: slashed string.
- */
- function strencode( $s );
- /**
- * Returns a wikitext link to the DB's website, e.g.,
- * return "[http://www.mysql.com/ MySQL]";
- * Should at least contain plain text, if for some reason
- * your database has no website.
- *
- * @return string: wikitext of a link to the server software's web site
- */
- static function getSoftwareLink();
- /**
- * A string describing the current software version, like from
- * mysql_get_server_info().
- *
- * @return string: Version information from the database server.
- */
- function getServerVersion();
- /**
- * A string describing the current software version, and possibly
- * other details in a user-friendly way. Will be listed on Special:Version, etc.
- * Use getServerVersion() to get machine-friendly information.
- *
- * @return string: Version information from the database server
- */
- function getServerInfo();
- }
- /**
- * Database abstraction object
- * @ingroup Database
- */
- abstract class DatabaseBase implements DatabaseType {
- # ------------------------------------------------------------------------------
- # Variables
- # ------------------------------------------------------------------------------
- protected $mLastQuery = '';
- protected $mDoneWrites = false;
- protected $mPHPError = false;
- protected $mServer, $mUser, $mPassword, $mDBname;
- /**
- * @var DatabaseBase
- */
- protected $mConn = null;
- protected $mOpened = false;
- protected $mTablePrefix;
- protected $mFlags;
- protected $mTrxLevel = 0;
- protected $mErrorCount = 0;
- protected $mLBInfo = array();
- protected $mFakeSlaveLag = null, $mFakeMaster = false;
- protected $mDefaultBigSelects = null;
- protected $mSchemaVars = false;
- protected $preparedArgs;
- protected $htmlErrors;
- protected $delimiter = ';';
- # ------------------------------------------------------------------------------
- # Accessors
- # ------------------------------------------------------------------------------
- # These optionally set a variable and return the previous state
- /**
- * A string describing the current software version, and possibly
- * other details in a user-friendly way. Will be listed on Special:Version, etc.
- * Use getServerVersion() to get machine-friendly information.
- *
- * @return string: Version information from the database server
- */
- public function getServerInfo() {
- return $this->getServerVersion();
- }
- /**
- * Boolean, controls output of large amounts of debug information.
- * @param $debug bool|null
- * - true to enable debugging
- * - false to disable debugging
- * - omitted or null to do nothing
- *
- * @return The previous value of the flag
- */
- function debug( $debug = null ) {
- return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
- }
- /**
- * Turns buffering of SQL result sets on (true) or off (false). Default is
- * "on".
- *
- * Unbuffered queries are very troublesome in MySQL:
- *
- * - If another query is executed while the first query is being read
- * out, the first query is killed. This means you can't call normal
- * MediaWiki functions while you are reading an unbuffered query result
- * from a normal wfGetDB() connection.
- *
- * - Unbuffered queries cause the MySQL server to use large amounts of
- * memory and to hold broad locks which block other queries.
- *
- * If you want to limit client-side memory, it's almost always better to
- * split up queries into batches using a LIMIT clause than to switch off
- * buffering.
- *
- * @param $buffer null|bool
- *
- * @return The previous value of the flag
- */
- function bufferResults( $buffer = null ) {
- if ( is_null( $buffer ) ) {
- return !(bool)( $this->mFlags & DBO_NOBUFFER );
- } else {
- return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
- }
- }
- /**
- * Turns on (false) or off (true) the automatic generation and sending
- * of a "we're sorry, but there has been a database error" page on
- * database errors. Default is on (false). When turned off, the
- * code should use lastErrno() and lastError() to handle the
- * situation as appropriate.
- *
- * @param $ignoreErrors bool|null
- *
- * @return bool The previous value of the flag.
- */
- function ignoreErrors( $ignoreErrors = null ) {
- return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
- }
- /**
- * Gets or sets the current transaction level.
- *
- * Historically, transactions were allowed to be "nested". This is no
- * longer supported, so this function really only returns a boolean.
- *
- * @param $level An integer (0 or 1), or omitted to leave it unchanged.
- * @return The previous value
- */
- function trxLevel( $level = null ) {
- return wfSetVar( $this->mTrxLevel, $level );
- }
- /**
- * Get/set the number of errors logged. Only useful when errors are ignored
- * @param $count The count to set, or omitted to leave it unchanged.
- * @return The error count
- */
- function errorCount( $count = null ) {
- return wfSetVar( $this->mErrorCount, $count );
- }
- /**
- * Get/set the table prefix.
- * @param $prefix The table prefix to set, or omitted to leave it unchanged.
- * @return The previous table prefix.
- */
- function tablePrefix( $prefix = null ) {
- return wfSetVar( $this->mTablePrefix, $prefix );
- }
- /**
- * Get properties passed down from the server info array of the load
- * balancer.
- *
- * @param $name string The entry of the info array to get, or null to get the
- * whole array
- *
- * @return LoadBalancer|null
- */
- function getLBInfo( $name = null ) {
- if ( is_null( $name ) ) {
- return $this->mLBInfo;
- } else {
- if ( array_key_exists( $name, $this->mLBInfo ) ) {
- return $this->mLBInfo[$name];
- } else {
- return null;
- }
- }
- }
- /**
- * Set the LB info array, or a member of it. If called with one parameter,
- * the LB info array is set to that parameter. If it is called with two
- * parameters, the member with the given name is set to the given value.
- *
- * @param $name
- * @param $value
- */
- function setLBInfo( $name, $value = null ) {
- if ( is_null( $value ) ) {
- $this->mLBInfo = $name;
- } else {
- $this->mLBInfo[$name] = $value;
- }
- }
- /**
- * Set lag time in seconds for a fake slave
- *
- * @param $lag int
- */
- function setFakeSlaveLag( $lag ) {
- $this->mFakeSlaveLag = $lag;
- }
- /**
- * Make this connection a fake master
- *
- * @param $enabled bool
- */
- function setFakeMaster( $enabled = true ) {
- $this->mFakeMaster = $enabled;
- }
- /**
- * Returns true if this database supports (and uses) cascading deletes
- *
- * @return bool
- */
- function cascadingDeletes() {
- return false;
- }
- /**
- * Returns true if this database supports (and uses) triggers (e.g. on the page table)
- *
- * @return bool
- */
- function cleanupTriggers() {
- return false;
- }
- /**
- * Returns true if this database is strict about what can be put into an IP field.
- * Specifically, it uses a NULL value instead of an empty string.
- *
- * @return bool
- */
- function strictIPs() {
- return false;
- }
- /**
- * Returns true if this database uses timestamps rather than integers
- *
- * @return bool
- */
- function realTimestamps() {
- return false;
- }
- /**
- * Returns true if this database does an implicit sort when doing GROUP BY
- *
- * @return bool
- */
- function implicitGroupby() {
- return true;
- }
- /**
- * Returns true if this database does an implicit order by when the column has an index
- * For example: SELECT page_title FROM page LIMIT 1
- *
- * @return bool
- */
- function implicitOrderby() {
- return true;
- }
- /**
- * Returns true if this database requires that SELECT DISTINCT queries require that all
- ORDER BY expressions occur in the SELECT list per the SQL92 standard
- *
- * @return bool
- */
- function standardSelectDistinct() {
- return true;
- }
- /**
- * Returns true if this database can do a native search on IP columns
- * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
- *
- * @return bool
- */
- function searchableIPs() {
- return false;
- }
- /**
- * Returns true if this database can use functional indexes
- *
- * @return bool
- */
- function functionalIndexes() {
- return false;
- }
- /**
- * Return the last query that went through DatabaseBase::query()
- * @return String
- */
- function lastQuery() {
- return $this->mLastQuery;
- }
- /**
- * Returns true if the connection may have been used for write queries.
- * Should return true if unsure.
- *
- * @return bool
- */
- function doneWrites() {
- return $this->mDoneWrites;
- }
- /**
- * Is a connection to the database open?
- * @return Boolean
- */
- function isOpen() {
- return $this->mOpened;
- }
- /**
- * Set a flag for this connection
- *
- * @param $flag Integer: DBO_* constants from Defines.php:
- * - DBO_DEBUG: output some debug info (same as debug())
- * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
- * - DBO_IGNORE: ignore errors (same as ignoreErrors())
- * - DBO_TRX: automatically start transactions
- * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
- * and removes it in command line mode
- * - DBO_PERSISTENT: use persistant database connection
- */
- function setFlag( $flag ) {
- $this->mFlags |= $flag;
- }
- /**
- * Clear a flag for this connection
- *
- * @param $flag: same as setFlag()'s $flag param
- */
- function clearFlag( $flag ) {
- $this->mFlags &= ~$flag;
- }
- /**
- * Returns a boolean whether the flag $flag is set for this connection
- *
- * @param $flag: same as setFlag()'s $flag param
- * @return Boolean
- */
- function getFlag( $flag ) {
- return !!( $this->mFlags & $flag );
- }
- /**
- * General read-only accessor
- *
- * @param $name string
- *
- * @return string
- */
- function getProperty( $name ) {
- return $this->$name;
- }
- /**
- * @return string
- */
- function getWikiID() {
- if ( $this->mTablePrefix ) {
- return "{$this->mDBname}-{$this->mTablePrefix}";
- } else {
- return $this->mDBname;
- }
- }
- /**
- * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
- *
- * @return string
- */
- public function getSchemaPath() {
- global $IP;
- if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
- return "$IP/maintenance/" . $this->getType() . "/tables.sql";
- } else {
- return "$IP/maintenance/tables.sql";
- }
- }
- # ------------------------------------------------------------------------------
- # Other functions
- # ------------------------------------------------------------------------------
- /**
- * Constructor.
- * @param $server String: database server host
- * @param $user String: database user name
- * @param $password String: database user password
- * @param $dbName String: database name
- * @param $flags
- * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
- */
- function __construct( $server = false, $user = false, $password = false, $dbName = false,
- $flags = 0, $tablePrefix = 'get from global'
- ) {
- global $wgDBprefix, $wgCommandLineMode;
- $this->mFlags = $flags;
- if ( $this->mFlags & DBO_DEFAULT ) {
- if ( $wgCommandLineMode ) {
- $this->mFlags &= ~DBO_TRX;
- } else {
- $this->mFlags |= DBO_TRX;
- }
- }
- /** Get the default table prefix*/
- if ( $tablePrefix == 'get from global' ) {
- $this->mTablePrefix = $wgDBprefix;
- } else {
- $this->mTablePrefix = $tablePrefix;
- }
- if ( $user ) {
- $this->open( $server, $user, $password, $dbName );
- }
- }
- /**
- * Called by serialize. Throw an exception when DB connection is serialized.
- * This causes problems on some database engines because the connection is
- * not restored on unserialize.
- */
- public function __sleep() {
- throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
- }
- /**
- * Same as new DatabaseMysql( ... ), kept for backward compatibility
- * @deprecated since 1.17
- *
- * @param $server
- * @param $user
- * @param $password
- * @param $dbName
- * @param $flags int
- * @return DatabaseMysql
- */
- static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
- wfDeprecated( __METHOD__, '1.17' );
- return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
- }
- /**
- * Same as new factory( ... ), kept for backward compatibility
- * @deprecated since 1.18
- * @see Database::factory()
- */
- public final static function newFromType( $dbType, $p = array() ) {
- wfDeprecated( __METHOD__, '1.18' );
- if ( isset( $p['tableprefix'] ) ) {
- $p['tablePrefix'] = $p['tableprefix'];
- }
- return self::factory( $dbType, $p );
- }
- /**
- * Given a DB type, construct the name of the appropriate child class of
- * DatabaseBase. This is designed to replace all of the manual stuff like:
- * $class = 'Database' . ucfirst( strtolower( $type ) );
- * as well as validate against the canonical list of DB types we have
- *
- * This factory function is mostly useful for when you need to connect to a
- * database other than the MediaWiki default (such as for external auth,
- * an extension, et cetera). Do not use this to connect to the MediaWiki
- * database. Example uses in core:
- * @see LoadBalancer::reallyOpenConnection()
- * @see ExternalUser_MediaWiki::initFromCond()
- * @see ForeignDBRepo::getMasterDB()
- * @see WebInstaller_DBConnect::execute()
- *
- * @param $dbType String A possible DB type
- * @param $p Array An array of options to pass to the constructor.
- * Valid options are: host, user, password, dbname, flags, tablePrefix
- * @return DatabaseBase subclass or null
- */
- public final static function factory( $dbType, $p = array() ) {
- $canonicalDBTypes = array(
- 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
- );
- $dbType = strtolower( $dbType );
- $class = 'Database' . ucfirst( $dbType );
- if( in_array( $dbType, $canonicalDBTypes ) || ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) ) {
- return new $class(
- isset( $p['host'] ) ? $p['host'] : false,
- isset( $p['user'] ) ? $p['user'] : false,
- isset( $p['password'] ) ? $p['password'] : false,
- isset( $p['dbname'] ) ? $p['dbname'] : false,
- isset( $p['flags'] ) ? $p['flags'] : 0,
- isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global'
- );
- } else {
- return null;
- }
- }
- protected function installErrorHandler() {
- $this->mPHPError = false;
- $this->htmlErrors = ini_set( 'html_errors', '0' );
- set_error_handler( array( $this, 'connectionErrorHandler' ) );
- }
- /**
- * @return bool|string
- */
- protected function restoreErrorHandler() {
- restore_error_handler();
- if ( $this->htmlErrors !== false ) {
- ini_set( 'html_errors', $this->htmlErrors );
- }
- if ( $this->mPHPError ) {
- $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
- $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
- return $error;
- } else {
- return false;
- }
- }
- /**
- * @param $errno
- * @param $errstr
- */
- protected function connectionErrorHandler( $errno, $errstr ) {
- $this->mPHPError = $errstr;
- }
- /**
- * Closes a database connection.
- * if it is open : commits any open transactions
- *
- * @return Bool operation success. true if already closed.
- */
- function close() {
- # Stub, should probably be overridden
- return true;
- }
- /**
- * @param $error String: fallback error message, used if none is given by DB
- */
- function reportConnectionError( $error = 'Unknown error' ) {
- $myError = $this->lastError();
- if ( $myError ) {
- $error = $myError;
- }
- # New method
- throw new DBConnectionError( $this, $error );
- }
- /**
- * The DBMS-dependent part of query()
- *
- * @param $sql String: SQL query.
- * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
- */
- protected abstract function doQuery( $sql );
- /**
- * Determine whether a query writes to the DB.
- * Should return true if unsure.
- *
- * @param $sql string
- *
- * @return bool
- */
- function isWriteQuery( $sql ) {
- return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
- }
- /**
- * Run an SQL query and return the result. Normally throws a DBQueryError
- * on failure. If errors are ignored, returns false instead.
- *
- * In new code, the query wrappers select(), insert(), update(), delete(),
- * etc. should be used where possible, since they give much better DBMS
- * independence and automatically quote or validate user input in a variety
- * of contexts. This function is generally only useful for queries which are
- * explicitly DBMS-dependent and are unsupported by the query wrappers, such
- * as CREATE TABLE.
- *
- * However, the query wrappers themselves should call this function.
- *
- * @param $sql String: SQL query
- * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
- * comment (you can use __METHOD__ or add some extra info)
- * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
- * maybe best to catch the exception instead?
- * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
- * for a successful read query, or false on failure if $tempIgnore set
- * @throws DBQueryError Thrown when the database returns an error of any kind
- */
- public function query( $sql, $fname = '', $tempIgnore = false ) {
- $isMaster = !is_null( $this->getLBInfo( 'master' ) );
- if ( !Profiler::instance()->isStub() ) {
- # generalizeSQL will probably cut down the query to reasonable
- # logging size most of the time. The substr is really just a sanity check.
- if ( $isMaster ) {
- $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
- $totalProf = 'DatabaseBase::query-master';
- } else {
- $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
- $totalProf = 'DatabaseBase::query';
- }
- wfProfileIn( $totalProf );
- wfProfileIn( $queryProf );
- }
- $this->mLastQuery = $sql;
- if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
- # Set a flag indicating that writes have been done
- wfDebug( __METHOD__ . ": Writes done: $sql\n" );
- $this->mDoneWrites = true;
- }
- # Add a comment for easy SHOW PROCESSLIST interpretation
- global $wgUser;
- if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
- $userName = $wgUser->getName();
- if ( mb_strlen( $userName ) > 15 ) {
- $userName = mb_substr( $userName, 0, 15 ) . '...';
- }
- $userName = str_replace( '/', '', $userName );
- } else {
- $userName = '';
- }
- $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
- # If DBO_TRX is set, start a transaction
- if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
- $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
- # avoid establishing transactions for SHOW and SET statements too -
- # that would delay transaction initializations to once connection
- # is really used by application
- $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
- if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 )
- $this->begin( __METHOD__ . " ($fname)" );
- }
- if ( $this->debug() ) {
- static $cnt = 0;
- $cnt++;
- $sqlx = substr( $commentedSql, 0, 500 );
- $sqlx = strtr( $sqlx, "\t\n", ' ' );
- $master = $isMaster ? 'master' : 'slave';
- wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
- }
- if ( istainted( $sql ) & TC_MYSQL ) {
- throw new MWException( 'Tainted query found' );
- }
- $queryId = MWDebug::query( $sql, $fname, $isMaster );
- # Do the query and handle errors
- $ret = $this->doQuery( $commentedSql );
- MWDebug::queryTime( $queryId );
- # Try reconnecting if the connection was lost
- if ( false === $ret && $this->wasErrorReissuable() ) {
- # Transaction is gone, like it or not
- $this->mTrxLevel = 0;
- wfDebug( "Connection lost, reconnecting...\n" );
- if ( $this->ping() ) {
- wfDebug( "Reconnected\n" );
- $sqlx = substr( $commentedSql, 0, 500 );
- $sqlx = strtr( $sqlx, "\t\n", ' ' );
- global $wgRequestTime;
- $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
- if ( $elapsed < 300 ) {
- # Not a database error to lose a transaction after a minute or two
- wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
- }
- $ret = $this->doQuery( $commentedSql );
- } else {
- wfDebug( "Failed\n" );
- }
- }
- if ( false === $ret ) {
- $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
- }
- if ( !Profiler::instance()->isStub() ) {
- wfProfileOut( $queryProf );
- wfProfileOut( $totalProf );
- }
- return $this->resultObject( $ret );
- }
- /**
- * Report a query error. Log the error, and if neither the object ignore
- * flag nor the $tempIgnore flag is set, throw a DBQueryError.
- *
- * @param $error String
- * @param $errno Integer
- * @param $sql String
- * @param $fname String
- * @param $tempIgnore Boolean
- */
- function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
- # Ignore errors during error handling to avoid infinite recursion
- $ignore = $this->ignoreErrors( true );
- ++$this->mErrorCount;
- if ( $ignore || $tempIgnore ) {
- wfDebug( "SQL ERROR (ignored): $error\n" );
- $this->ignoreErrors( $ignore );
- } else {
- $sql1line = str_replace( "\n", "\\n", $sql );
- wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
- wfDebug( "SQL ERROR: " . $error . "\n" );
- throw new DBQueryError( $this, $error, $errno, $sql, $fname );
- }
- }
- /**
- * Intended to be compatible with the PEAR::DB wrapper functions.
- * http://pear.php.net/manual/en/package.database.db.intro-execute.php
- *
- * ? = scalar value, quoted as necessary
- * ! = raw SQL bit (a function for instance)
- * & = filename; reads the file and inserts as a blob
- * (we don't use this though...)
- *
- * This function should not be used directly by new code outside of the
- * database classes. The query wrapper functions (select() etc.) should be
- * used instead.
- *
- * @param $sql string
- * @param $func string
- *
- * @return array
- */
- function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
- /* MySQL doesn't support prepared statements (yet), so just
- pack up the query for reference. We'll manually replace
- the bits later. */
- return array( 'query' => $sql, 'func' => $func );
- }
- /**
- * Free a prepared query, generated by prepare().
- * @param $prepared
- */
- function freePrepared( $prepared ) {
- /* No-op by default */
- }
- /**
- * Execute a prepared query with the various arguments
- * @param $prepared String: the prepared sql
- * @param $args Mixed: Either an array here, or put scalars as varargs
- *
- * @return ResultWrapper
- */
- function execute( $prepared, $args = null ) {
- if ( !is_array( $args ) ) {
- # Pull the var args
- $args = func_get_args();
- array_shift( $args );
- }
- $sql = $this->fillPrepared( $prepared['query'], $args );
- return $this->query( $sql, $prepared['func'] );
- }
- /**
- * Prepare & execute an SQL statement, quoting and inserting arguments
- * in the appropriate places.
- *
- * This function should not be used directly by new code outside of the
- * database classes. The query wrapper functions (select() etc.) should be
- * used instead.
- *
- * @param $query String
- * @param $args ...
- *
- * @return ResultWrapper
- */
- function safeQuery( $query, $args = null ) {
- $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
- if ( !is_array( $args ) ) {
- # Pull the var args
- $args = func_get_args();
- array_shift( $args );
- }
- $retval = $this->execute( $prepared, $args );
- $this->freePrepared( $prepared );
- return $retval;
- }
- /**
- * For faking prepared SQL statements on DBs that don't support
- * it directly.
- * @param $preparedQuery String: a 'preparable' SQL statement
- * @param $args Array of arguments to fill it with
- * @return string executable SQL
- */
- function fillPrepared( $preparedQuery, $args ) {
- reset( $args );
- $this->preparedArgs =& $args;
- return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
- array( &$this, 'fillPreparedArg' ), $preparedQuery );
- }
- /**
- * preg_callback func for fillPrepared()
- * The arguments should be in $this->preparedArgs and must not be touched
- * while we're doing this.
- *
- * @param $matches Array
- * @return String
- */
- function fillPreparedArg( $matches ) {
- switch( $matches[1] ) {
- case '\\?': return '?';
- case '\\!': return '!';
- case '\\&': return '&';
- }
- list( /* $n */ , $arg ) = each( $this->preparedArgs );
- switch( $matches[1] ) {
- case '?': return $this->addQuotes( $arg );
- case '!': return $arg;
- case '&':
- # return $this->addQuotes( file_get_contents( $arg ) );
- throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
- default:
- throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
- }
- }
- /**
- * Free a result object returned by query() or select(). It's usually not
- * necessary to call this, just use unset() or let the variable holding
- * the result object go out of scope.
- *
- * @param $res Mixed: A SQL result
- */
- function freeResult( $res ) {
- }
- /**
- * Simple UPDATE wrapper.
- * Usually throws a DBQueryError on failure.
- * If errors are explicitly ignored, returns success
- *
- * This function exists for historical reasons, DatabaseBase::update() has a more standard
- * calling convention and feature set
- *
- * @param $table string
- * @param $var
- * @param $value
- * @param $cond
- * @param $fname string
- *
- * @return bool
- */
- function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
- $table = $this->tableName( $table );
- $sql = "UPDATE $table SET $var = '" .
- $this->strencode( $value ) . "' WHERE ($cond)";
- return (bool)$this->query( $sql, $fname );
- }
- /**
- * A SELECT wrapper which returns a single field from a single result row.
- *
- * Usually throws a DBQueryError on failure. If errors are explicitly
- * ignored, returns false on failure.
- *
- * If no result rows are returned from the query, false is returned.
- *
- * @param $table string|array Table name. See DatabaseBase::select() for details.
- * @param $var string The field name to select. This must be a valid SQL
- * fragment: do not use unvalidated user input.
- * @param $cond string|array The condition array. See DatabaseBase::select() for details.
- * @param $fname string The function name of the caller.
- * @param $options string|array The query options. See DatabaseBase::select() for details.
- *
- * @return false|mixed The value from the field, or false on failure.
- */
- function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
- $options = array() )
- {
- if ( !is_array( $options ) ) {
- $options = array( $options );
- }
- $options['LIMIT'] = 1;
- $res = $this->select( $table, $var, $cond, $fname, $options );
- if ( $res === false || !$this->numRows( $res ) ) {
- return false;
- }
- $row = $this->fetchRow( $res );
- if ( $row !== false ) {
- return reset( $row );
- } else {
- return false;
- }
- }
- /**
- * Returns an optional USE INDEX clause to go after the table, and a
- * string to go at the end of the query.
- *
- * @param $options Array: associative array of options to be turned into
- * an SQL query, valid keys are listed in the function.
- * @return Array
- * @see DatabaseBase::select()
- */
- function makeSelectOptions( $options ) {
- $preLimitTail = $postLimitTail = '';
- $startOpts = '';
- $noKeyOptions = array();
- foreach ( $options as $key => $option ) {
- if ( is_numeric( $key ) ) {
- $noKeyOptions[$option] = true;
- }
- }
- if ( isset( $options['GROUP BY'] ) ) {
- $gb = is_array( $options['GROUP BY'] )
- ? implode( ',', $options['GROUP BY'] )
- : $options['GROUP BY'];
- $preLimitTail .= " GROUP BY {$gb}";
- }
- if ( isset( $options['HAVING'] ) ) {
- $preLimitTail .= " HAVING {$options['HAVING']}";
- }
- if ( isset( $options['ORDER BY'] ) ) {
- $ob = is_array( $options['ORDER BY'] )
- ? implode( ',', $options['ORDER BY'] )
- : $options['ORDER BY'];
- $preLimitTail .= " ORDER BY {$ob}";
- }
- // if (isset($options['LIMIT'])) {
- // $tailOpts .= $this->limitResult('', $options['LIMIT'],
- // isset($options['OFFSET']) ? $options['OFFSET']
- // : false);
- // }
- if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
- $postLimitTail .= ' FOR UPDATE';
- }
- if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
- $postLimitTail .= ' LOCK IN SHARE MODE';
- }
- if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
- $startOpts .= 'DISTINCT';
- }
- # Various MySQL extensions
- if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
- $startOpts .= ' /*! STRAIGHT_JOIN */';
- }
- if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
- $startOpts .= ' HIGH_PRIORITY';
- }
- if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
- $startOpts .= ' SQL_BIG_RESULT';
- }
- if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
- $startOpts .= ' SQL_BUFFER_RESULT';
- }
- if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
- $startOpts .= ' SQL_SMALL_RESULT';
- }
- if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
- $startOpts .= ' SQL_CALC_FOUND_ROWS';
- }
- if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
- $startOpts .= ' SQL_CACHE';
- }
- if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
- $startOpts .= ' SQL_NO_CACHE';
- }
- if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
- $useIndex = $this->useIndexClause( $options['USE INDEX'] );
- } else {
- $useIndex = '';
- }
- return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
- }
- /**
- * Execute a SELECT query constructed using the various parameters provided.
- * See below for full details of the parameters.
- *
- * @param $table String|Array Table name
- * @param $vars String|Array Field names
- * @param $conds String|Array Conditions
- * @param $fname String Caller function name
- * @param $options Array Query options
- * @param $join_conds Array Join conditions
- *
- * @param $table string|array
- *
- * May be either an array of table names, or a single string holding a table
- * name. If an array is given, table aliases can be specified, for example:
- *
- * array( 'a' => 'user' )
- *
- * This includes the user table in the query, with the alias "a" available
- * for use in field names (e.g. a.user_name).
- *
- * All of the table names given here are automatically run through
- * DatabaseBase::tableName(), which causes the table prefix (if any) to be
- * added, and various other table name mappings to be performed.
- *
- *
- * @param $vars string|array
- *
- * May be either a field name or an array of field names. The field names
- * here are complete fragments of SQL, for direct inclusion into the SELECT
- * query. Expressions and aliases may be specified as in SQL, for example:
- *
- * array( 'MAX(rev_id) AS maxrev' )
- *
- * If an expression is given, care must be taken to ensure that it is
- * DBMS-independent.
- *
- *
- * @param $conds string|array
- *
- * May be either a string containing a single condition, or an array of
- * conditions. If an array is given, the conditions constructed from each
- * element are combined with AND.
- *
- * Array elements may take one of two forms:
- *
- * - Elements with a numeric key are interpreted as raw SQL fragments.
- * - Elements with a string key are interpreted as equality conditions,
- * where the key is the field name.
- * - If the value of such an array element is a scalar (such as a
- * string), it will be treated as data and thus quoted appropriately.
- * If it is null, an IS NULL clause will be added.
- * - If the value is an array, an IN(...) clause will be constructed,
- * such that the field name may match any of the elements in the
- * array. The elements of the array will be quoted.
- *
- * Note that expressions are often DBMS-dependent in their syntax.
- * DBMS-independent wrappers are provided for constructing several types of
- * expression commonly used in condition queries. See:
- * - DatabaseBase::buildLike()
- * - DatabaseBase::conditional()
- *
- *
- * @param $options string|array
- *
- * Optional: Array of query options. Boolean options are specified by
- * including them in the array as a string value with a numeric key, for
- * example:
- *
- * array( 'FOR UPDATE' )
- *
- * The supported options are:
- *
- * - OFFSET: Skip this many rows at the start of the result set. OFFSET
- * with LIMIT can theoretically be used for paging through a result set,
- * but this is discouraged in MediaWiki for performance reasons.
- *
- * - LIMIT: Integer: return at most this many rows. The rows are sorted
- * and then the first rows are taken until the limit is reached. LIMIT
- * is applied to a result set after OFFSET.
- *
- * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
- * changed until the next COMMIT.
- *
- * - DISTINCT: Boolean: return only unique result rows.
- *
- * - GROUP BY: May be either an SQL fragment string naming a field or
- * expression to group by, or an array of such SQL fragments.
- *
- * - HAVING: A string containing a HAVING clause.
- *
- * - ORDER BY: May be either an SQL fragment giving a field name or
- * expression to order by, or an array of such SQL fragments.
- *
- * - USE INDEX: This may be either a string giving the index name to use
- * for the query, or an array. If it is an associative array, each key
- * gives the table name (or alias), each value gives the index name to
- * use for that table. All strings are SQL fragments and so should be
- * validated by the caller.
- *
- * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
- * instead of SELECT.
- *
- * And also the following boolean MySQL extensions, see the MySQL manual
- * for documentation:
- *
- * - LOCK IN SHARE MODE
- * - STRAIGHT_JOIN
- * - HIGH_PRIORITY
- * - SQL_BIG_RESULT
- * - SQL_BUFFER_RESULT
- * - SQL_SMALL_RESULT
- * - SQL_CALC_FOUND_ROWS
- * - SQL_CACHE
- * - SQL_NO_CACHE
- *
- *
- * @param $join_conds string|array
- *
- * Optional associative array of table-specific join conditions. In the
- * most common case, this is unnecessary, since the join condition can be
- * in $conds. However, it is useful for doing a LEFT JOIN.
- *
- * The key of the array contains the table name or alias. The value is an
- * array with two elements, numbered 0 and 1. The first gives the type of
- * join, the second is an SQL fragment giving the join condition for that
- * table. For example:
- *
- * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
- *
- * @return ResultWrapper. If the query returned no rows, a ResultWrapper
- * with no rows in it will be returned. If there was a query error, a
- * DBQueryError exception will be thrown, except if the "ignore errors"
- * option was set, in which case false will be returned.
- */
- function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
- $options = array(), $join_conds = array() ) {
- $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
- return $this->query( $sql, $fname );
- }
- /**
- * The equivalent of DatabaseBase::select() except that the constructed SQL
- * is returned, instead of being immediately executed.
- *
- * @param $table string|array Table name
- * @param $vars string|array Field names
- * @param $conds string|array Conditions
- * @param $fname string Caller function name
- * @param $options string|array Query options
- * @param $join_conds string|array Join conditions
- *
- * @return SQL query string.
- * @see DatabaseBase::select()
- */
- function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
- if ( is_array( $vars ) ) {
- $vars = implode( ',', $vars );
- }
- $options = (array)$options;
- if ( is_array( $table ) ) {
- $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
- ? $options['USE INDEX']
- : array();
- if ( count( $join_conds ) || count( $useIndex ) ) {
- $from = ' FROM ' .
- $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
- } else {
- $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
- }
- } elseif ( $table != '' ) {
- if ( $table[0] == ' ' ) {
- $from = ' FROM ' . $table;
- } else {
- $from = ' FROM ' . $this->tableName( $table );
- }
- } else {
- $from = '';
- }
- list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
- if ( !empty( $conds ) ) {
- if ( is_array( $conds ) ) {
- $conds = $this->makeList( $conds, LIST_AND );
- }
- $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
- } else {
- $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
- }
- if ( isset( $options['LIMIT'] ) ) {
- $sql = $this->limitResult( $sql, $options['LIMIT'],
- isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
- }
- $sql = "$sql $postLimitTail";
- if ( isset( $options['EXPLAIN'] ) ) {
- $sql = 'EXPLAIN ' . $sql;
- }
- return $sql;
- }
- /**
- * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
- * that a single row object is returned. If the query returns no rows,
- * false is returned.
- *
- * @param $table string|array Table name
- * @param $vars string|array Field names
- * @param $conds array Conditions
- * @param $fname string Caller function name
- * @param $options string|array Query options
- * @param $join_conds array|string Join conditions
- *
- * @return ResultWrapper|bool
- */
- function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
- $options = array(), $join_conds = array() )
- {
- $options = (array)$options;
- $options['LIMIT'] = 1;
- $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
- if ( $res === false ) {
- return false;
- }
- if ( !$this->numRows( $res ) ) {
- return false;
- }
- $obj = $this->fetchObject( $res );
- return $obj;
- }
- /**
- * Estimate rows in dataset.
- *
- * MySQL allows you to estimate the number of rows that would be returned
- * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
- * index cardinality statistics, and is notoriously inaccurate, especially
- * when large numbers of rows have recently been added or deleted.
- *
- * For DBMSs that don't support fast result size estimation, this function
- * will actually perform the SELECT COUNT(*).
- *
- * Takes the same arguments as DatabaseBase::select().
- *
- * @param $table String: table name
- * @param Array|string $vars : unused
- * @param Array|string $conds : filters on the table
- * @param $fname String: function name for profiling
- * @param $options Array: options for select
- * @return Integer: row count
- */
- public function estimateRowCount( $table, $vars = '*', $conds = '',
- $fname = 'DatabaseBase::estimateRowCount', $options = array() )
- {
- $rows = 0;
- $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
- if ( $res ) {
- $row = $this->fetchRow( $res );
- $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
- }
- return $rows;
- }
- /**
- * Removes most variables from an SQL query and replaces them with X or N for numbers.
- * It's only slightly flawed. Don't use for anything important.
- *
- * @param $sql String A SQL Query
- *
- * @return string
- */
- static function generalizeSQL( $sql ) {
- # This does the same as the regexp below would do, but in such a way
- # as to avoid crashing php on some large strings.
- # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
- $sql = str_replace ( "\\\\", '', $sql );
- $sql = str_replace ( "\\'", '', $sql );
- $sql = str_replace ( "\\\"", '', $sql );
- $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
- $sql = preg_replace ( '/".*"/s', "'X'", $sql );
- # All newlines, tabs, etc replaced by single space
- $sql = preg_replace ( '/\s+/', ' ', $sql );
- # All numbers => N
- $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
- return $sql;
- }
- /**
- * Determines whether a field exists in a table
- *
- * @param $table String: table name
- * @param $field String: filed to check on that table
- * @param $fname String: calling function name (optional)
- * @return Boolean: whether $table has filed $field
- */
- function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
- $info = $this->fieldInfo( $table, $field );
- return (bool)$info;
- }
- /**
- * Determines whether an index exists
- * Usually throws a DBQueryError on failure
- * If errors are explicitly ignored, returns NULL on failure
- *
- * @param $table
- * @param $index
- * @param $fname string
- *
- * @return bool|null
- */
- function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
- $info = $this->indexInfo( $table, $index, $fname );
- if ( is_null( $info ) ) {
- return null;
- } else {
- return $info !== false;
- }
- }
- /**
- * Query whether a given table exists
- *
- * @param $table string
- * @param $fname string
- *
- * @return bool
- */
- function tableExists( $table, $fname = __METHOD__ ) {
- $table = $this->tableName( $table );
- $old = $this->ignoreErrors( true );
- $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
- $this->ignoreErrors( $old );
- return (bool)$res;
- }
- /**
- * mysql_field_type() wrapper
- * @param $res
- * @param $index
- * @return string
- */
- function fieldType( $res, $index ) {
- if ( $res instanceof ResultWrapper ) {
- $res = $res->result;
- }
- return mysql_field_type( $res, $index );
- }
- /**
- * Determines if a given index is unique
- *
- * @param $table string
- * @param $index string
- *
- * @return bool
- */
- function indexUnique( $table, $index ) {
- $indexInfo = $this->indexInfo( $table, $index );
- if ( !$indexInfo ) {
- return null;
- }
- return !$indexInfo[0]->Non_unique;
- }
- /**
- * Helper for DatabaseBase::insert().
- *
- * @param $options array
- * @return string
- */
- function makeInsertOptions( $options ) {
- return implode( ' ', $options );
- }
- /**
- * INSERT wrapper, inserts an array into a table.
- *
- * $a may be either:
- *
- * - A single associative array. The array keys are the field names, and
- * the values are the values to insert. The values are treated as data
- * and will be quoted appropriately. If NULL is inserted, this will be
- * converted to a database NULL.
- * - An array with numeric keys, holding a list of associative arrays.
- * This causes a multi-row INSERT on DBMSs that support it. The keys in
- * each subarray must be identical to each other, and in the same order.
- *
- * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
- * returns success.
- *
- * $options is an array of options, with boolean options encoded as values
- * with numeric keys, in the same style as $options in
- * DatabaseBase::select(). Supported options are:
- *
- * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
- * any rows which cause duplicate key errors are not inserted. It's
- * possible to determine how many rows were successfully inserted using
- * DatabaseBase::affectedRows().
- *
- * @param $table String Table name. This will be passed through
- * DatabaseBase::tableName().
- * @param $a Array of rows to insert
- * @param $fname String Calling function name (use __METHOD__) for logs/profiling
- * @param $options Array of options
- *
- * @return bool
- */
- function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
- # No rows to insert, easy just return now
- if ( !count( $a ) ) {
- return true;
- }
- $table = $this->tableName( $table );
- if ( !is_array( $options ) ) {
- $options = array( $options );
- }
- $options = $this->makeInsertOptions( $options );
- if ( isset( $a[0] ) && is_array( $a[0] ) ) {
- $multi = true;
- $keys = array_keys( $a[0] );
- } else {
- $multi = false;
- $keys = array_keys( $a );
- }
- $sql = 'INSERT ' . $options .
- " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
- if ( $multi ) {
- $first = true;
- foreach ( $a as $row ) {
- if ( $first ) {
- $first = false;
- } else {
- $sql .= ',';
- }
- $sql .= '(' . $this->makeList( $row ) . ')';
- }
- } else {
- $sql .= '(' . $this->makeList( $a ) . ')';
- }
- return (bool)$this->query( $sql, $fname );
- }
- /**
- * Make UPDATE options for the DatabaseBase::update function
- *
- * @param $options Array: The options passed to DatabaseBase::update
- * @return string
- */
- function makeUpdateOptions( $options ) {
- if ( !is_array( $options ) ) {
- $options = array( $options );
- }
- $opts = array();
- if ( in_array( 'LOW_PRIORITY', $options ) ) {
- $opts[] = $this->lowPriorityOption();
- }
- if ( in_array( 'IGNORE', $options ) ) {
- $opts[] = 'IGNORE';
- }
- return implode( ' ', $opts );
- }
- /**
- * UPDATE wrapper. Takes a condition array and a SET array.
- *
- * @param $table String name of the table to UPDATE. This will be passed through
- * DatabaseBase::tableName().
- *
- * @param $values Array: An array of values to SET. For each array element,
- * the key gives the field name, and the value gives the data
- * to set that field to. The data will be quoted by
- * DatabaseBase::addQuotes().
- *
- * @param $conds Array: An array of conditions (WHERE). See
- * DatabaseBase::select() for the details of the format of
- * condition arrays. Use '*' to update all rows…
Large files files are truncated, but you can click here to view the full file